function $ajax
时间: 2023-10-31 09:56:51 浏览: 95
$.ajax()方法详解
$ajax is not a built-in function in JavaScript. However, it is commonly used as a shorthand for making asynchronous HTTP requests using the XMLHttpRequest or Fetch API. It allows you to send and receive data from a server without refreshing the entire web page.
Here is an example of how you can create a simple AJAX function using the XMLHttpRequest object:
```javascript
function $ajax(method, url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send(JSON.stringify(data));
}
```
You can use this function to make AJAX requests by providing the HTTP method (e.g., GET, POST), URL, data to send (optional), and a callback function to handle the response.
Note that the above example is a basic implementation, and there are more advanced libraries and frameworks available that provide additional features and handle cross-browser compatibility.
阅读全文