Is there a way to send data using the POST method without a form and without refreshing the page using only pure JavaScript (not jQuery $.post()
)? Maybe httprequest
or something else (just can't find it now)?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The [new-ish at the time of writing in 2017] Fetch API is intented to make GET requests easy, but it is able to POST as well.
If you are as lazy as me (or just prefer a shortcut/helper):
navigator.sendBeacon()
If you simply need to
POST
data and do not require a response from the server, the shortest solution would be to usenavigator.sendBeacon()
:There is an easy method to wrap your data and send it to server as if you were sending an HTML form using
POST
. you can do that usingFormData
object as following:now you can handle the data on the server-side just like the way you deal with reugular HTML Forms.
Additional Info
It is advised that you must not set Content-Type header when sending FormData since the browser will take care of that.
You can send it and insert the data to the body:
By the way, for get request:
Also, RESTful lets you get data back from a POST request.
JS (put in static/hello.html to serve via Python):
Python server (for testing):
Console log (chrome):
Console log (firefox):
Console log (Edge):
Python log:
You can use the
XMLHttpRequest
object as follows:That code would post
someStuff
tourl
. Just make sure that when you create yourXMLHttpRequest
object, it will be cross-browser compatible. There are endless examples out there of how to do that.