我无法将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