vanilla js vs jQuery ajax call

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 18:22:01

问题


I want to do an ajax call with vanilla js.

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

Vanilla 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");

The vanilla js call just logs this to the console:

"Success: [object Object]" 
Array [  ]

Can someone tell me what I am doing wrong?


回答1:


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.




回答2:


Beyond printing out r.responseText to the console, you can also inspect the HTTP response from dev tools built into the browser itself.

On Firefox, for instance:

  1. Tools -> Web Developer -> Network (this should open a panel listing all the HTTP requests and responses)
  2. Go through the process you use to execute your AJAX call
  3. Look at the corresponding HTTP request by clicking on the item in the list in the panel shown in step 1 (a panel on the right should appear with more details about the request and subsequent response)

Digging around in these tools can give you a lot of insight into the the HTTP request your code is making and the values it's getting back in the response.

A similar process can be performed for all the major browsers out there.




回答3:


You can use this simple and lightweight Ajax module with the following syntax:

import {ajax} from '/path/to/ajax.min.js';

ajax('https://api_url.com')
.data('key-1','Value-1')
.data('key-2','Value-2')
.send()
.then((data) => { console.log ('success', data) })
.catch((status) => { console.log ('failed', status)} );


来源:https://stackoverflow.com/questions/27296673/vanilla-js-vs-jquery-ajax-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!