香草js vs jQuery ajax调用

问题描述:

我想用香草js进行ajax调用.

I want to do an ajax call with vanilla js.

jQuery 中,我有这个有效的ajax调用:

In jQuery, I have this working ajax call:

$.ajax({
    url:"/faq/ajax",
    datatype: 'json',
    type:"POST",
    data: {search:'banana'},
    success:function(r) {
    console.log(r['name'])
    }
});

香草JS:

var search = document.getElementById('searchbarfaq').value;
var r = new XMLHttpRequest();
r.open("POST", "/faq/ajax", true);
r.onreadystatechange = function () {
  if (r.readyState != 4 || r.status != 200) return;
  console.log("Success: " + JSON.parse(r.responseText));
  var a = JSON.parse(r.responseText);
  console.log(a.name); //also tried a['name']...
};
r.send("search=banana");

香草js调用只是将其记录到控制台:

The vanilla js call just logs this to the console:

"Success: [object Object]" 
Array [  ]

有人可以告诉我我在做什么错吗?

Can someone tell me what I am doing wrong?

您尚未告诉服务器如何在请求中编码数据.

You haven't told the server how you are encoding the data in the request.

r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

大概您用于处理数据的任何服务器端处理程序都无法正确解析数据,因此无法找到所需的数据,然后返回一个空白数组作为结果.

Presumably whatever server side handler you are using to process the data isn't parsing it correctly, so isn't finding the data it needs, and then returns a blank array as the result.