在Ajax中調(diào)用后端接口的方式有多種。以下是常見的幾種方法:
var xhr = new XMLHttpRequest();
xhr.open("GET", "backend-api-url", true);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// 處理響應(yīng)數(shù)據(jù)
}
};
xhr.send();
$.ajax({
url: "backend-api-url",
method: "GET",
success: function(response) {
// 處理響應(yīng)數(shù)據(jù)
}
});
fetch("backend-api-url", {
method: "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
// 處理響應(yīng)數(shù)據(jù)
});
以上是使用GET方法調(diào)用后端接口的示例,如果需要使用其他HTTP方法,可以在請求中設(shè)置method屬性為對應(yīng)的值。此外,還可以通過設(shè)置data參數(shù)來傳遞請求數(shù)據(jù)。具體的調(diào)用方式還取決于后端接口的要求和項目中使用的框架和庫。