jQuery Ajax表单数据设置转换为纯javascript



找到答案感谢Patrick Evans:

window.onload = function()
{
var data = new FormData();
data.append("gcd", "gcd");
data.append("name", "name");

ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(options.data || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default: 
options.success(http_request.responseText);
break;
case 'json': 
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}

这是我的Ajax测试javascript使用jQuery和纯javascript Ajax:

window.onload = function()
{
var url = "GRNM";
var data = {
gcd: "gcd",
name: "name"
};

$.ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});

ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}

纯Javascript Ajax:

var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(JSON.stringify(options.data) || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default: 
options.success(http_request.responseText);
break;
case 'json': 
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}

结果如下:

jQuery:我可以成功获取值数据

General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 200 
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: keep-alive
Content-Length: 43
Content-Type: application/json
Date: Fri, 27 Aug 2021 06:20:37 GMT
Keep-Alive: timeout=60
Request Headers:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 17
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
gcd: gcd
name: name

纯Javascript:我找不到数据

General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 400 
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: close
Content-Language: en-US
Content-Type: text/html;charset=Shift_JIS
Date: Fri, 27 Aug 2021 06:20:37 GMT
Transfer-Encoding: chunked
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 27
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
{"gcd":"gcd","name":"name"}: 

我的Spring Boot Controller找不到来自纯javascript的gcdname参数,因为表单数据格式不同。我也试过使用FormData(),但不能使它工作。

My Form Data变成这样:

Form Data:
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name: "gcd"
gcd
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name="name"
name
------WebKitFormBoundaryLgD8tjkxnVk4hfiE--

我也尝试将http_request.send(JSON.stringify(options.data) || null);更改为http_request.send(options.data || null);,但没有工作。

如何实现与jQuery相同的结果?我怎么能通过我的var data对象控制器使用Ajax POST相同的jQuery?

您需要为正确的内容提供正确的内容类型。

如果你想发送JSON文本,你必须使用application/jsoncontent-type

http_request.setRequestHeader('Content-Type', 'application/json');
http_request.send(JSON.stringify(options.data));

如果你想使用FormData对象,你需要multipart/form-datacontent-type

let fd = new FormData();
for(let key in options.data){
fd.append(key,options.data[key]);
}
//don't need to explicitly set content-type when sending FormData
//it will automatically do that
//http_request.setRequestHeader('Content-Type', 'multipart/form-data');
http_request.send(fd);

如果你只是想使用你的对象,你需要将它转换为前面提到的方法之一,或者从它创建一个参数字符串,并使用application/x-www-form-urlencodedcontent-type

//builds a param=value&param2=value2 type of string from your options.data object
let paramStrings = [];
for(let key in options.data){
paramStrings.push(`${key}=${options.data[key]}`);
}
let data = paramStrings.join('&');
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.send(data);

最新更新