Use JavaScript functions to implement AJAX requests and data acquisition
1. Introduction to AJAX
AJAX (Asynchronous JavaScript and XML) is a method used to implement AJAX on web pages Asynchronous data interaction technology. Through AJAX, we can send a request to the server and get the data returned by the server without refreshing the entire page. This improves the user experience and makes the page more interactive and dynamic.
2. Implementation steps of AJAX request
3. Code example of using JavaScript function to implement AJAX request
Create XMLHttpRequest object
function createHttpRequest() { if (window.XMLHttpRequest) { // 支持现代浏览器 return new XMLHttpRequest(); } else if (window.ActiveXObject) { // 兼容IE6及更早版本 return new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("浏览器不支持AJAX!"); return null; } }
Send GET Request and get data
function getData(url, callback) { var xhr = createHttpRequest(); if (xhr) { xhr.open("GET", url, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { callback(xhr.responseText); } }; xhr.send(); } }
Send POST request and get data
function postData(url, data, callback) { var xhr = createHttpRequest(); if (xhr) { xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { callback(xhr.responseText); } }; xhr.send(data); } }
4. Usage example
Suppose we have a The backend API interface can return a piece of data in JSON format. Use the above code to make an AJAX request and get data.
Use GET request to obtain data
var url = "http://example.com/api/getData"; getData(url, function(response) { // 在这里处理获取到的数据 console.log(response); });
Use POST request to send data and get the return result
var url = "http://example.com/api/submitData"; var data = "username=John&password=123456"; postData(url, data, function(response) { // 在这里处理返回的结果 console.log(response); });
Summary:
Using JavaScript functions to implement AJAX requests and data acquisition can make web pages more dynamic and interactive. By creating an XMLHttpRequest object, setting the request method and URL, sending the request and processing the data returned by the server, we can realize the function of asynchronous data interaction. Obtain data through GET requests or send data using POST requests, and process the results returned by the server in the callback function, allowing the web page to interact with the server and dynamically display the data.
The above is the detailed content of Use JavaScript functions to implement AJAX requests and data acquisition. For more information, please follow other related articles on the PHP Chinese website!