我正在为GET方法编写web API。此方法将返回JSON对象作为响应。我需要一个动作过滤器方法或一个事件,当浏览器成功接收到响应时自动调用。
以下内容改编自Nicholas Zakas的Professional JavaScript for Web Developers (3rd Edition):
Ajax功能:function Ajax() {
var xhr, responseObj, getCompletionFunction;
var completionFunction;
this.setGetCompletionFunction = function (value) { getCompletionFunction = value; }
this.getRequest = function (url) {
completionFunction = getCompletionFunction;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = readyStateChangeFunction;
xhr.open("get", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(null);
}
function readyStateChangeFunction() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
responseObj = JSON.parse(xhr.responseText);
completionFunction(responseObj);
} else {
var errorMessage = xhr.status;
responseObj = { errorMessages: ["An error of type " + errorMessage + " occurred while attempting to reach the server."] };
completionFunction(responseObj);
}
}
}
}
感兴趣的行是:
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
确定Web Api调用是否成功。如果是,则该函数解析响应并将其输入回调。否则,回调函数将返回一个错误消息。
Ajax函数示例:
var ajax = new Ajax();
var completionFunction = function (data) {
var returnedData = data;
}
ajax.setGetCompletionFunction(completionFunction);
ajax.getRequest("/api/Home/1");