[javascript]key, value 방식의 오브젝트를 post 방식으로 전달

/**
 *  key, map 형태의 오브젝트를 POST방식으로 전송한다. (jquery 방식)
 *  사용방법 :
 *          let param = {name : "홍길동", age : 20};
 *          postForm("/postUrl", param);
 *
 */
function postForm(url, parameters) {
    var form = $('<form>');

    form.attr("method", "post");
    form.attr("action", url);

    $.each(parameters, function(key, value) {
        var field = $('<input>');

        field.attr("type", "hidden");
        field.attr("name", key);
        field.attr("value", value);

        form.append(field);
    });

    $(document.body).append(form);
    form.submit();
}

/**
 * sends a request to the specified url from a form. this will change the window location.
 * @param {string} path the path to send the post request to
 * @param {object} params the paramiters to add to the url
 * @param {string} [method=post] the method to use on the form
 * 사용방법 : post('/contact/', {name: 'Johnny Bravo'});
 */

function post(path, params, method='post') {

  // The rest of this code assumes you are not using a library.
  // It can be made less wordy if you use one.
  const form = document.createElement('form');
  form.method = method;
  form.action = path;

  for (const key in params) {
    if (params.hasOwnProperty(key)) {
      const hiddenField = document.createElement('input');
      hiddenField.type = 'hidden';
      hiddenField.name = key;
      hiddenField.value = params[key];

      form.appendChild(hiddenField);
    }
  }

  document.body.appendChild(form);
  form.submit();
}

// 출처 : https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다