我正在写一篇关于 JavaScript 的文章,如果 url、方法和数据是方法接收的参数,那么成功和错误又如何呢?它们是参数还是其他名称?
$.ajax({
url: "url",
method: "get",
data: {
"someData":someData
},
success: function (data) {
alert(data);
},
error: function (errorThrown) {
alert(errorThrown);
}
});
最佳答案
成功和错误都是回调函数,
In short success and error are to specify what to do in case of success or failure of the request respectively.
成功
Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions.
错误
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn.
那么它是如何工作的?
AJAX 使用 XMLHttpRequest 对象与服务器通信
用户从 UI 发送请求,并且 JavaScript 调用转到 XMLHttpRequest 对象。
HTTP 请求通过 XMLHttpRequest 对象发送到服务器。
服务器使用JSP、PHP、Servlet、ASP.net等与数据库交互
已检索数据。
服务器将 XML 数据或 JSON 数据发送到 XMLHttpRequest 回调函数。
成功完成 Ajax 请求后调用的成功回调
在发出请求时出现任何错误时调用的失败回调
HTML 和 CSS 数据显示在浏览器上。
关于javascript - jQuery ajax 调用中的 "succes"和 "error"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46328493/