js之原生ajax、Jquery-$.ajax、自定义ajax(post请求、get请求)
原生AJAX请求示例:
var xhr = new XMLHttpRequest();
xhr.open("POST", "your_url", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send("param1=value1¶m2=value2");
JQuery $.ajax 请求示例:
$.ajax({
type: "POST",
url: "your_url",
data: { param1: "value1", param2: "value2" },
success: function(response){
console.log(response);
},
error: function(xhr, status, error){
console.error("An error occurred: " + status + "\nError: " + error);
}
});
自定义AJAX POST请求示例:
function postRequest(url, data, callback) {
var xhr = new XMLHttpRequest();
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);
}
postRequest("your_url", "param1=value1¶m2=value2", function(response){
console.log(response);
});
自定义AJAX GET请求示例:
function getRequest(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.send();
}
getRequest("your_url", function(response){
console.log(response);
});
评论已关闭