How to make an AJAX call without jQuery?

2018-12-30 23:32发布

How to make an AJAX call using JavaScript, without using jQuery?

22条回答
人间绝色
2楼-- · 2018-12-31 00:02

I know this is a fairly old question, but there is now a nicer API available natively in newer browsers. The fetch() method allow you to make web requests. For example, to request some json from /get-data:

var opts = {
  method: 'GET',      
  headers: {}
};
fetch('/get-data', opts).then(function (response) {
  return response.json();
})
.then(function (body) {
  //doSomething with body;
});

See here for more details.

查看更多
闭嘴吧你
3楼-- · 2018-12-31 00:04

Use XMLHttpRequest.

Simple GET request

httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()

Simple POST request

httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')

We can specify that the request should be asynchronous(true), the default, or synchronous(false) with an optional third argument.

// Make a synchronous GET request
httpRequest.open('GET', 'http://www.example.org/some.file', false)

We can set headers before calling httpRequest.send()

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

We can handle the response by setting httpRequest.onreadystatechange to a function before calling httpRequest.send()

httpRequest.onreadystatechange = function(){
  // Process the server response here.
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      alert(httpRequest.responseText);
    } else {
      alert('There was a problem with the request.');
    }
  }
}
查看更多
还给你的自由
4楼-- · 2018-12-31 00:04

From youMightNotNeedJquery.com + JSON.stringify

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(JSON.stringify(data));
查看更多
初与友歌
5楼-- · 2018-12-31 00:06

Using @Petah answer above as a huge help resource. I've written my own AJAX module here called AJ for short: https://github.com/NightfallAlicorn/AJ Not everything is tested yet but it works for me with get and post for JSON. You're free to copy and use the source as you wish. I hadn't seen a marked accepted answer yet so I presume this is okay to post.

查看更多
登录 后发表回答