2017-06-05 88 views
0

我無法將JSON對象發送到XMLHttpRequest()。但是,如果我通過send()發送字符串數據,它將起作用。例如,下面的代碼工作:無法將JSON對象發送到XMLHttpRequest

var xhr = new XMLHttpRequest(); 
var url = 'https://xyz.info/api/contacts'; 
xhr.open("POST", url,true); 
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

xhr.onreadystatechange = function() {//Call a function when the state changes. 
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { 
       // Request finished. Do processing here. 
    } 
} 
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456"); 

不過,如果我嘗試使用JSON發送數據時,其職位無關的網址。以下代碼不起作用。

var xhr = new XMLHttpRequest(); 
var url = 'https://xyz.info/api/contacts'; 
    xhr.open("POST", url,true); 
    //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhr.setRequestHeader("Content-Type", "application/json"); 

    xhr.onreadystatechange = function() {//Call a function when the state changes. 
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { 
      // Request finished. Do processing here. 
     } 
    } 
    xhr.send(JSON.stringify({ 
        'apikey' :'ee6915d4ee4b4df66bba82277e3', 
        'firstname' : 'Kumar', 
        'lastname' : 'Sunder', 
        'phone':'5557773334' 
    }));   
+1

在第二個示例中,您正在發送一個字符串。不完全是一個JSON對象。 – Matthias

+0

@Matthias雖然是一個JavaScript對象的字符串表示。我仍然不知道什麼是json對象(不存在)。 – James

+0

愚蠢的問題,但是API支持「application/json」類型的帖子嗎?你有沒有檢查瀏覽器devtools網絡標籤,看看你的代碼實際上發佈什麼? – James

回答

0

您在兩次通話中發送的信息非常不同。一些示例代碼:

var _stringify = JSON.stringify({ 'apikey' :'ee6915d4ee4b4df66bba82277e3', 'firstname' : 'Kumar', 'lastname' : 'Sunder', 'phone':'5557773334' }); console.log(_stringify); var _orig = "apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456" var _encoded = encodeURI(_stringify); console.log(_orig); console.log(_encoded); 當你的原始字符串打印到控制檯日誌,它看起來像您期望:

apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456 當JSON.stringify的結果打印到控制檯,它返回: {"apikey":"ee6915d4ee4b4df66bba82277e3","firstname":"Kumar","lastname":"Sunder","phone":"5557773334"} 也就是說,它帶有大量額外的雙引號和左右括號。如果你想把所有這些都作爲一個字符串來發送(就像在你的第一個例子中那樣),你需要對JSON.stringify調用的結果進行URI編碼。這是「_encoded」變量發生的情況,其中包含: %7B%22apikey%22:%22ee6915d4ee4b4df66bba82277e3%22,%22firstname%22:%22Kumar%22,%22lastname%22:%22Sunder%22,%22phone%22:%225557773334%22%7D

0

您正在通過POST操作發送,但隨後通過url字符串發送數據。如果你想以這種方式發送,你需要將它設置爲GET。

+0

我沒有看到。第一種情況是通過傳統的html表單類型的POST,第二種情況是通過應用程序/ json類型的POST。 'application/x-www-form-urlencoded'的數據序列化看起來與querystring類似。 – James