代码之家  ›  专栏  ›  技术社区  ›  Mike

在jquery中保存临时Ajax参数

  •  0
  • Mike  · 技术社区  · 15 年前

    我正在开发一个编写了大量脚本的Web应用程序,现在正在做一些错误处理。但要做到这一点,我需要一种方法来访问为特定的Ajax请求提供给jQuery的Ajax参数。我在jquery.com上没有找到任何关于它的信息,所以我想问你们是否知道如何实现这一点。

    下面是一个示例,说明了我希望如何按代码方式执行该操作:

    function add_recording(filename) {
        updateCounter('addRecording','up');
        jQuery.ajax({
            url: '/cgi-bin/apps/ajax/Storyboard',
            type: 'POST',
            dataType: 'json',
            data: {
                sid: sid,
                story: story,
                screen_id: screen_id,
                mode: 'add_record',
                file_name: filename
            },
            success: function(json) {
                updateCounter('addRecording','down');
                id = json[0].id;
                create_record(id, 1, 1, json);
            },
            error: function() {
                updateCounter('addRecording','error',hereBeData);
            }
        })
    }
    

    这里的数据是所需的数据(如URL、类型、数据类型和实际数据)。

    updateCounter是一个用新信息更新状态区域的函数。它也是一个区域,在该区域中,用户会收到错误通知,并根据在此数据中收集的信息,在该区域中生成一个“取消”和“重试”按钮。

    3 回复  |  直到 15 年前
        1
  •  3
  •   gnarf    15 年前

    不管打什么电话 complete() success() error() - this 将等于传递给$.Ajax()的对象,尽管url和数据的值并不总是完全相同-它将转换参数并编辑一点左右的对象。但是,您可以向对象添加自定义键以记住您的内容:

    $.ajax({
      url: '/',
      data: {test:'test'},
      // we make a little 'extra copy' here in case we need it later in an event
      remember: {url:'/', data:{test:'test'}},
    
      error: function() {
        alert(this.remember.data.test + ': error');
      },
      success: function() {
        alert(this.remember.data.test + ': success');
      },
      complete: function() {
        alert(this.remember.data.url + ': complete');
      }
    });
    

    当然,由于您最初是从某个源设置此数据,因此您可以依赖变量范围来为您保留它:

    $("someelement").click(function() {
       var theURL = $(this).attr('href');
       var theData = { text: $(this).text(); }
       $.ajax({ 
         url: theUrl,
         data: theData,
         error: function() {
           alert('There was an error loading '+theURL);
         } 
       });
    
       // but look out for situations like this: 
       theURL = 'something else';
    });
    
        2
  •  1
  •   Andy Gaskell    15 年前

    查看您可以获得的参数 callback for error .

    function (XMLHttpRequest, textStatus, errorThrown) {
      // typically only one of textStatus or errorThrown 
      // will have info
      this; // the options for this ajax request
    }
    
        3
  •  0
  •   redsquare    15 年前

    您可以使用Ajax complete event 它将传递给您用于请求的AjaxOptions。成功请求和失败请求都将完全激发。

    complete : function (event, XMLHttpRequest, ajaxOptions) {
       //store ajaxOptions here
       //1 way is to use the .data on the body for example
       $('body').data('myLastAjaxRequest', ajaxOptions);
    }
    

    然后您可以使用

    var ajaxOptions = $('body').data('myLastAjaxRequest');