2017-06-05 84 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