Use GET to request data to submit, mainly throughSplice the query parameters after the URLThe specific steps are as follows:
1. Construct the URL with parameters
Add the data toKey = Value
After the form of is spliced into the URL, use it between multiple parameters.&
connect. For example:
var url = "/api?param1=value1¶m2=value2";
If the parameter value contains special characters (such as spaces, Chinese, etc.), it is requiredencodeURIComponent()
Encoding to ensure that the URL is legal:
var paramValue = "Special Value/Space"; var encodedParam = encodeURIComponent(paramValue); var url = `/api?param=${encodedParam}`;
2. Initiate a GET request
useXMLHttpRequest
The object initiates a request and passes the constructed URL inopen()
method:
var xhr = new XMLHttpRequest(); ("GET", url, true); // The third parameter is whether it is asynchronous, generally set to true(); // GET Requested send() Usually no parameters(The data is already here URL middle)
Example:
= function() { ("helloBtn").onclick = function() { var xhr = new XMLHttpRequest(); // Splicing parameters (assuming that user information is obtained, the parameters are user name and age) var params = "username=John&age=30"; var url = "/ajax/ajaxrequest1?" + params; ("GET", url, true); = function() { if ( === 4 && === 200) { // Process response data (); } }; (); }; };
Notice:
- The parameters requested by the GET are exposed to the URL.Not suitable for transferring sensitive data(such as password).
- Different browsers have restrictions on URL length (usually about 4KB) and are not suitable for transferring large amounts of data.
In this way, data can be submitted to the server in the GET request of AJAX.
This is the article about how to submit data for AJAX get request. For more related content for AJAX get request, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!