How to make an AJAX call using JavaScript, without using jQuery?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- Carriage Return (ASCII chr 13) is missing from tex
- void before promise syntax
- Keeping track of variable instances
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
:See here for more details.
Use XMLHttpRequest.
Simple GET request
Simple POST request
We can specify that the request should be asynchronous(true), the default, or synchronous(false) with an optional third argument.
We can set headers before calling
httpRequest.send()
We can handle the response by setting
httpRequest.onreadystatechange
to a function before callinghttpRequest.send()
From youMightNotNeedJquery.com +
JSON.stringify
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.