理解jQuery的jqXHR [英] Understanding jQuery's jqXHR

查看:61
本文介绍了理解jQuery的jqXHR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组 $。get()请求我需要重构以包含失败回调。请求的格式为

I have a set of $.get() requests that I need to refactor to include a failure callback. The requests are of the form

$.get(url,
      {},
      function(data) {//success, do work
      //work
      },'json');//or 'html'

根据jQuery API,我只需添加一个jqHXR对象。所以在我的情况下,我相信我应该这样做

According to the jQuery API, I simply add a jqHXR object. So in my case, I believe I should do

var jqxhr =  $.get(url,
          {},
          function(data) {//success, do work
          //work
          },'json').error(function() { alert("error"); });//or 'html'

我不明白示例。我想它可以用于建立一个回调链。我希望错误执行错误,并成功执行成功。那么,这是正确的吗?

I don't understand the reason for the second success callback in the example. I suppose it could be there for setting up a callback chain. I want error to execute in error, and success to execute on success. So, is this correct?

推荐答案

我认为示例中的第二个成功回调就是说明,使用这种语法,你可以拥有多个处理程序对于成功错误,以及完成事件。在标准的jQuery .ajax()方法中,您只能为每个事件分配一个处理程序。我无法想象一个需要多个处理程序的例子,但它确实看起来更清晰,更像是使用的标准jQuery习语

I think the second success callback in the example is just there to illustrate that, using this syntax, you can have multiple handlers for success, error, and complete events. In the standard jQuery .ajax() method, you can only assign a single handler to each of these events. I can't think offhand of an example that would require multiple handlers, but it does seem a little clearer and more like the standard jQuery idiom to use

$.get('my_url.php')
    .success(handlerOne)
    .success(handlerTwo);

而不是

$.get('my_url.php', function(data, textStatus, jqXHR) {
    handlerOne(data, textStatus, jqXHR);
    handlerTwo(data, textStatus, jqXHR);
});

但是,在您的情况下,转换 $。get()语句到 $ .ajax()。大多数jQuery程序员可能更熟悉 $。ajax()语法,因为您不需要特殊功能(多个处理程序,后请求处理程序分配)在其他语法中,没有理由不使用 $ .ajax()

In your case, though, it might be easier and cleaner to just convert your $.get() statements to $.ajax(). The $.ajax() syntax is probably more familiar to most jQuery programmers, and since you don't need the special functionality (multiple handlers, post-request handler assignment) available in the other syntax, there's no reason not to just use $.ajax():

$.ajax({
    url: url,
    success: function(data) {
        // success, do work
    },
    error: function(data) {
        // error, handle failure
    },
    dataType:'json'
});

这篇关于理解jQuery的jqXHR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆