【问题标题】:How can I pass copies of object to the function in the .done() of a $.ajax?如何将对象的副本传递给 $.ajax 的 .done() 中的函数?
【发布时间】:2012-10-31 20:49:09
【问题描述】:

我有以下代码:

function doDialogAjax(link: Link. modal: Modal) {
    $.ajax( link.Url,
    {
        cache: false,
        dataType: 'html'
    })
        .done(onDialogDone)
        .fail(onDialogFail);
}

function onDialogDone(data: any, textStatus: string, jqXHR: JQueryXHR) {
    var x = data;
    // I need to access link.abc and modal.def properties here
}

如何将链接对象发送到我的 onDialogDone() 函数?一世 似乎记得有一些方法可以发送指定的上下文信息对象,但我找不到任何例子。

【问题讨论】:

    标签: javascript ajax jquery typescript


    【解决方案1】:

    您可以使用上下文键在回调中更改 this 的值:

    function doDialogAjax(link: Link. modal: Modal) {
        $.ajax( link.Url,
        {
            cache: false,
            dataType: 'html',
            context: {
               link: link,
               modal: modal
            }
        })
            .done(onDialogDone)
            .fail(onDialogFail);
    }
    
    function onDialogDone(data: any, textStatus: string, jqXHR: JQueryXHR) {
        var x = data;
        // this refers to the context-object, with keys [link, modal]
        console.log(this.link);
        console.log(this.modal)
    }
    

    【讨论】:

      【解决方案2】:
      .done(onDialogDone({link : link, modal : modal}, 'success', data))
      

      这样的?

      【讨论】:

      • 好吧,也许我不够清楚。我是这样说的:$.ajax( link.Url, { cache: false, dataType: 'html', context: { link: link, modal: modal } }) .done(onDialogDone({link : link, modal : modal}, 'success', data)), .fail(onDialogFail);
      • 这没什么区别。函数名后跟左括号表示立即调用。
      猜你喜欢
      • 2017-09-18
      • 2011-12-07
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多