无法将JSON对象发送到XMLHttpRequest

时间:2017-06-05 19:24:35

标签: javascript json xmlhttprequest

我无法将JSON对象发送到XMLHttpRequest()。但是,如果我通过send()发送字符串数据,它可以工作。例如,以下代码有效:

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

2 个答案:

答案 0 :(得分:0)

您正在通过POST操作发送,但之后通过url字符串发送数据。如果你想以这种方式发送它,你需要将它设置为GET。

答案 1 :(得分: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