通过POST发送JavaScript对象数组

时间:2014-09-03 19:17:13

标签: javascript arrays json post google-chrome-extension

我有一个对象数组,我试图发送到我的PHP脚本。在发送数组之前,我可以访问其中的所有数据,一切都在那里。一旦到达PHP,var_dump将返回NULL。我不太确定如何发送数据。

chrome.storage.local.get('object', function (object) {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("POST", "http://example.com/php.php", true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    var uid = 2;

    JSON.stringify(object);
    xmlhttp.send("json=" + object + "&uid=" + uid);
});

数组:

var obj = [
    {
        "key": "val",
        "key2": "val2"
    },
    {
        "key": "val",
        "key2": "val2"
    }
]

obj.push({"key":val,"key2":val2});
chrome.storage.local.set({'object':obj});

1 个答案:

答案 0 :(得分:3)

这一行:

JSON.stringify(object);

没有任何用处:您从JSON.stringify()丢弃了返回的值。代替:

object = JSON.stringify(object);

会保留它。

你真的应该对你的参数进行编码:

xmlhttp.send("json=" + encodeURIComponent(object) + "&uid=" + encodeURIComponent(uid));
相关问题