发送使用javascript AJAX数组 [英] Sending an array using javascript ajax

查看:81
本文介绍了发送使用javascript AJAX数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery的我能做到这一点。

In jquery I can do this

myAray=['abc', '123', 'more'];
$.post('myscript.php', {data:myAray}, function(data){
    alert(data);
});

我能如何使用普通的JavaScript是一回事吗?我想用POST方法发送一个数组来我的PHP脚本。我发现这样的例子很多,但所有的人都jquery相关。

How can I do the same thing using plain javascript ? I want to send an array to my php script using POST method. I have found so many examples but all of them are jquery related.

在此先感谢。

推荐答案

您必须使用 XMLHtt prequest 和序列化数组自己:

You will have to use XMLHttpRequest and serialize the array yourself:

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 AJAX数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆