在 jquery 中我可以做到这一点
myAray=['abc', '123', 'more'];
$.post('myscript.php', {data:myAray}, function(data){
alert(data);
});
如何使用纯 javascript 做同样的事情?我想使用 POST 方法将数组发送到我的 php 脚本。我找到了很多示例,但所有示例都与 jquery 相关。
提前致谢。
最佳答案
您将不得不使用 XMLHttpRequest
并自行序列化数组:
function ajax(myArray) {
var xmlHTTP;
if (window.XMLHttpRequest) {
xmlHTTP = new XMLHttpRequest();
} else {
xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHTTP.onreadystatechange = function () {
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
// do whatever it is you want to do
}
}
//Serialize the data
var queryString = "";
for(var i = 0; i < myArray.length; i++) {
queryString += "myArray=" + myArray[i];
//Append an & except after the last element
if(i < myArray.length - 1) {
queryString += "&";
}
}
xmlHTTP.open("POST", "www.myurl.com", true);
xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHTTP.send(queryString);
}
关于javascript - 使用javascript ajax发送数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12187564/