作者:林姗飘零1999 | 来源:互联网 | 2023-06-13 11:37
ImpassinganarrayonaPOSTrequestusingjQuery,howeverIdontunderstandhowtodothesamew
I'm passing an array on a POST request using jQuery, however I don't understand how to do the same with "vanilla" Javascript. This is my jQuery:
我正在使用jQuery向POST请求传递一个数组,但是我不知道如何使用“香草”Javascript实现同样的操作。这是我的jQuery:
// Request using jQuery
$.ajax({type:'POST',url:'insert-user.php',data: {myArray: myArray},
success:function(data_response){
console.log("jQuery, got data back, response: "+data_response);
}});
This is currently how I'm trying to do it with plain js:
这是我目前尝试用普通js做的:
// Request using plain js
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.Onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log("JS, got data back, response: "+xmlhttp.responseText);
}
}
xmlhttp.open("POST","insert-user.php",true);
xmlhttp.send({myArray: myArray});
2 个解决方案
1
The .send()
method accepts a string which is the POST data to be sent in the request. In jQuery, the data
property allows you to pass an object (which you have), but behind the scenes, jQuery converts the object into a key/value pairs format.
send()方法接受一个字符串,该字符串是在请求中发送的POST数据。在jQuery中,数据属性允许您传递一个对象(您有),但是在幕后,jQuery将对象转换为键/值对格式。
This is the format that you must pass to .send()
because it doesn't automatically convert objects into the key/value string.
这是必须传递给.send()的格式,因为它不会自动地将对象转换为键/值字符串。
For example, to send myArray
with three elements:
例如,向myArray发送三个元素:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send('myArray[]=first&myArray[]=second&myArray[]=third');
Remember to include the header, to tell the server side which format you are sending POST data in.
记住要包含报头,告诉服务器端要发送的是哪种格式的POST数据。
A function to convert a simple 1 dimensional array to this format could look like:
将一个简单的一维数组转换成这种格式的函数可以是:
function arrayToKeyValueString(name, arr){
var str = name + '[]=';
for(var i=0; i
When working with plain Javascript ajax, it's often easier to just JSON encode data and send the string instead of trying to build the key/value string.
在使用普通Javascript ajax时,只对数据进行JSON编码并发送字符串通常比尝试构建键/值字符串更容易。
xmlhttp.send('myArray=' + encodeURIComponent(JSON.stringify(myArray)));