簡體   English   中英

將回調和其他參數傳遞給jQuery ajax成功嗎?

[英]Passing a callback and other parameters to jQuery ajax success?

我寫了一個函數,允許回調傳遞給它。 然后,我想同時使用ajax repsonse和另一個參數來執行該操作。

我的問題是執行了回調,並且當我單步執行代碼時,似乎使用適當的參數調用了該函數,但是,當實際進入回調函數時,第一個參數采用我分配給的值第二個參數,第二個參數是undefined

這是我的功能:

namespace = {
fetch : function(sr, count, callback) {
    srCount = count ? count : '25'
    var sub;
    if (sr == 'frontpage'){
        sub = '';
    }else{
        sub = 'foo/' + sr + '/';
    };
    $.ajax({
        url: "http://www.example.com/"+sub+ ".json?count=" + count,
        dataType: "json",
        success: function(msg)
        {
            callback.call(msg, count)
        }
    })
};

現在,當我這樣稱呼它時:

mynamespace.fetch($(this).attr('href'), 25, true, another namespace.createPost);

我希望callback.call(msg, count)解析為callback.call(/*the ajax response*/, 25);

但是,當我運行它時,我得到msg == 25count == 'undefined' 我茫然為什么...

.call調用具有第一個參數給出的顯式上下文的函數,因此callback.call(msg, count)調用將msg設置為上下文的回調函數(此調用的回調函數內的this值)並count為第一個參數。

因此,您可能需要callback( msg, count )callback.call( namespace, msg, count ); 這意味着回調中的this namespace將引用該調用的namespace

$.ajax()函數具有一個上下文參數,您可以將其用於此目的。

$.ajax({
  url: "http://www.example.com/"+sub+ ".json?count=" + count,
  context: "hello",
  dataType: "json",
  success: function(msg)
  {

    // here 'this' will be the 'hello' you specified for context while making the call.

    callback.call(msg, count)
  }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM