如何格式化数据以发送像jquery请求一样格式化的香草xhr

iovurdzv  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(323)

我有一个post XHEREQUEST,它在jquery中可以正常工作,但在vanilla js中不能。
因为我正在尝试学习js的所有内部工作,所以我希望使用尽可能多的普通代码。我知道FetchAPI,但我对这一切都是新手,我真的想更好地理解。因此,这是我目前面临的问题(一个多星期以来):
我有这样的代码,它可以工作:

let packg = {
        schema: 'string',
        table: 'anotherString'
    };

    const packgJSON = JSON.stringify(packg);

    $.ajax({
        type: 'POST',
        url: 'php/get_data.php',
        data: {'content': packgJSON}
    });

这是firefox开发者工具的结果,它与我的php文件完美配合:

当我尝试编写vanilla js时,如下所示:

const xhr = new XMLHttpRequest();

    xhr.open('POST', 'php/get_data.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    let packg = {
        schema: 'string',
        table: 'anotherString'
    };

    const packgJSON = JSON.stringify(packg);

    xhr.send({'content': packgJSON});

这是我得到的结果:

我不明白我该如何格式化文件 .send() 内容,以便像jquery请求一样格式化。我尝试了在mdn、w3schools中找到的其他选项,您可能不需要jquery等,但请求与jquery不同。我显然没有理解js对象和字符串的基本概念,但我完全不理解我应该做什么。

dm7nw8vv

dm7nw8vv1#

在vanilla js中,您的请求将如下所示

var http = new XMLHttpRequest();
var url = '/api/endpoint';
var params = 'orem=ipsum&name=binny' // Or your json;
http.open('POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

首先,创建一个新的xmlhttprequest,打开请求并提供方法和url

http.open('POST', url, true);

第三个参数是使请求像mdn文档中提到的那样异步
可选的布尔参数,默认为true,指示是否异步执行操作。如果此值为false,则在收到响应之前,send()方法不会返回。如果为true,则使用事件侦听器提供已完成事务的通知。如果multipart属性为true,则必须为true,否则将引发异常。
然后将请求与正文一起作为参数发送
http.send(params);
您可以使用这些事件侦听器侦听请求中的更改和响应

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
a11xaf1n

a11xaf1n2#

XMLHttpRequest.send 不像jquery ajax那样将普通对象作为参数。
但是,您可以使用该对象创建 URLSearchParams 对象并将其传递给发送

const xhr = new XMLHttpRequest();

xhr.open('POST', 'php/get_data.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

let packg = {
    schema: 'string',
    table: 'anotherString'
};

const packgJSON = JSON.stringify(packg);
var data = new URLSearchParams({'content': packgJSON})
xhr.send(data);

相关问题