我無法將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'
}));
在第二個示例中,您正在發送一個字符串。不完全是一個JSON對象。 – Matthias
@Matthias雖然是一個JavaScript對象的字符串表示。我仍然不知道什麼是json對象(不存在)。 – James
愚蠢的問題,但是API支持「application/json」類型的帖子嗎?你有沒有檢查瀏覽器devtools網絡標籤,看看你的代碼實際上發佈什麼? – James