简体   繁体   中英

In JS, how to make a POST given a URL and a application/x-www-form-urlencoded string?

I have an application/x-www-form-urlencoded string and a destination URL. How do I make the browser open that URL and use the string as the POST body?

EDIT : I know how to do that with a URL and an array (eg this ), so a fool proof way to parse the string to an array would be an answer as well

Warning: Completely untested code follows.

function post_form(url, body) {
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = url;

    var kvs = body.split('&');
    for (var i = 0; i < kvs.length; i++) {
        var kv = kvs[i];
        var k, v, p = kv.indexOf('=');
        if (p >= 0) {
            k = kv.substring(0, p);
            v = kv.substring(p + 1);
        } else {
            k = kv;
            v = '';
        }
        k = decodeURIComponent(k);
        v = decodeURIComponent(v);

        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = k;
        input.value = v;
        form.appendChild(input);
    }

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

you can use jquery to post ajax link to ajax properties and default values . here is the post example

JQuery ajax request has default value

contentType : 'application/x-www-form-urlencoded; charset=UTF-8'

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: successcallback,
  dataType: dataType
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM