javascript - jQuery ajax 调用中的 "succes"和 "error"是什么?

标签 javascript jquery ajax

我正在写一篇关于 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.

来自Jquery API

成功

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 对象与服务器通信

enter image description here

  1. 用户从 UI 发送请求,并且 JavaScript 调用转到 XMLHttpRequest 对象。

  2. HTTP 请求通过 XMLHttpRequest 对象发送到服务器。

  3. 服务器使用JSP、PHP、Servlet、ASP.net等与数据库交互

  4. 已检索数据。

  5. 服务器将 XML 数据或 JSON 数据发送到 XMLHttpRequest 回调函数。

    • 成功完成 Ajax 请求后调用的成功回调

    • 在发出请求时出现任何错误时调用的失败回调

  6. HTML 和 CSS 数据显示在浏览器上。

关于javascript - jQuery ajax 调用中的 "succes"和 "error"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46328493/

相关文章:

php - 在复选框选择上提交表单

javascript - 为什么我的 'for' 循环函数不起作用?

jquery - 如何使用 Jquery 终端作为 Quake(如控制台)和示例中的 RPC

javascript - 如何在使用 AJAX 时使用 header ?

Javascript 事件 - 同时按住 CTRL 键并将鼠标悬停在按钮上

javascript - 检查值并分配 TRUE 的更短方法

javascript - 禁用链接或阻止浏览器重定向

javascript - 在函数中使用 jQuery .append()?

asp.net - MVC AJAX 的 Jquery 或基本 XmlHttpRequest

javascript - 我如何告诉 jQuery 忽略空的服务器响应?