2014-09-03 58 views
1

发送JavaScript对象的数组我有我尝试发送到我的PHP脚本对象的数组。在发送数组之前,我可以访问它中的所有数据,所有内容都在那里。一旦它到达PHP var_dump返回NULL。我不太确定如何发送数据。通过POST

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}); 

回答

3

这条线:

JSON.stringify(object); 

没有任何用处:你是从JSON.stringify()扔掉返回值。相反:

object = JSON.stringify(object); 

将保持它。

你真的应该过于编码的参数:完美

xmlhttp.send("json=" + encodeURIComponent(object) + "&uid=" + encodeURIComponent(uid)); 
+0

作品,谢谢。我无法相信我没有注意到这一点。 – callmexshadow 2014-09-03 19:27:55