2014-09-03 59 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