2010-09-12 25 views
4

我需要返回動態加載的內容。我認爲這是做到這一點的方法,但該函數返回空白。我需要做什麼才能設置htmlCode以及從jQuery.ajax檢索到的html代碼?如何獲取此函數以返回使用jQuery.ajax檢索的值?

// Get directory listing 
    function getHTML(instance, current_path, dir) { 
    var htmlCode = ''; 

     jQuery.ajax({ 
      type: "POST", 
      url: "../wp-content/plugins/wp-filebrowser/jquery.php", 
      dataType: 'html', 
      data: {instance: instance, current_path: current_path, dir: dir}, 
      success: function(html){ 
       htmlCode = html; 
      }, 
      error: function(e) { 
      htmlCode = '[Error] ' + e; 
      } 
     }); 

     return htmlCode; 
    } 
+0

什麼版本?請參閱http://api.jquery.com/jQuery.ajax/例如 – Ashley 2010-09-12 18:11:51

+0

這是最新版本 - 1.4我認爲。 – Steven 2010-09-12 18:13:38

回答

5

發生這種情況是因爲ajax請求需要一些時間來獲取html,並且您的return語句在html準備好之前觸發。 Javascript代碼執行不會等待您的html返回。您可以通過刪除退貨並放置兩個警報來實際看到此情況。在成功事件中放入一個alert,並在其中放置返回語句。第二個alert會提醒。因此,即使您的html被提取,但它實際上永遠不會成功返回到調用函數,因爲時間html已經準備好了return語句。

您可以使用callback如果嚴格想要的功能getHtml()返回(以及實際call back)的HTML作爲輸出,否則你可以使用尼克建議的方式。

這裏是如何使用的回調: -

function getHTML(instance, current_path, dir,callback) 
{ 
    var htmlCode = ''; 

    jQuery.ajax({ 
     type: "POST", 
     url: "../wp-content/plugins/wp-filebrowser/jquery.php", 
     dataType: 'html', 
     data: {instance: instance, current_path: current_path, dir: dir}, 
     success: function(html){ 

     callback(html); //instead of a return 

     }, 
     error: function(e) { 
     htmlCode = '[Error] ' + e; 
     } 
    }); 

}

呼叫這樣的功能 -

getHTML(instance, current_path, dir, 
    function(html) 
    { 
     //Write code to use the html here - this will run when the getHTML() function does callback with the output html 
    } 
); 

注意callback參數的函數定義getHTML(例如, current_path,dir,callback)以及被調用函數中相應的function(html){}部分。

這樣,你實際上定義: -

  • 調用的函數,以call back來電功能,當輸出就緒
  • 和調用函數時收到的call back做一些事情。
+0

這裏有兩件事,你的語法關閉的回調風格,並沒有必要爲您的示例創建一個匿名函數,您可以直接傳遞函數引用:) – 2010-09-12 18:17:17

+0

對不起,我沒有完全明白你的意思。語法錯誤在哪裏? – 2010-09-12 18:24:10

+0

@sandeepan - 'function(html))'應該是'function(html)':) – 2010-09-12 18:25:09

3

這是一個異步操作,所以你不能真正迴歸這樣的...不是沒有發出請求同步(async: true選項),但我反對這項建議...因爲它鎖定了瀏覽器的請求的持續時間。您不能返回,因爲success回調在異步時在後面的之後纔會發生,因此請求運行後您的htmlCode = html;代碼尚未運行。

這是一個更好的方法來調用什麼從success回調需要一旦你的數據準備好,例如:

success: function(html){ 
    doSomethingWithHtml(html); 
}, 

或更簡潔地針對特定的單行情況:

success: doSomethingWithHtml, 
+0

我在成功回調中應用了html。但是由於我需要檢索不同的HTML,我希望通過創建一個通用函數來保存一些代碼,從而避免出現多個幾乎相同的代碼/函數。 'instance'變量決定從'jquery.php'返回的HTML。 – Steven 2010-09-12 22:37:52

+0

@Steven - 聽起來你可以使用一個普通函數並將它用作你的'成功',然後你甚至可以把它傳遞給'$ .ajaxSetup({success:generalFunction});'在給定的頁面上不要重複這個。 – 2010-09-12 22:58:19

相關問題