簡體   English   中英

如何將列表從一個功能附加到另一個

[英]How do I append list from one function to another

我試圖將數據從成功處理程序列表追加到表行,例如

function Table(data) {
    var rows = '';
    rows += '<tr......>'
}

function functionTwo() {
    $.ajax({
        ..........
    success: function (data) {
        $('#tabletr:last').after(rows);
    }
});

我編寫了兩個簡單的函數,在Table()函數中,我正在構建一個通過+ =”行填充的表。 如果functionTwo()成功,則應將來自結果的數據增益附加在Table函數中的+ =”行之后。

我該怎么做?

在Table函數外部全局聲明行,或者像這樣返回行並修復選擇器"#table tr:last"

function Table(data) {
var rows = '';
rows += '<tr......>'
return rows;
}

 function functionTwo() {
$.ajax({
..........
success: function (data) {
$('#table tr:last').after(Table(data)); //Call table here
}
});

您錯過了空間#table tr:last

var rows = '';
     function Table(data) {
    rows = '';
    rows += '<tr......>'
}

function functionTwo() {
    $.ajax({
        ..........
    success: function (data) {
        $('#table tr:last').after(rows);
    }
});

請記住,這是一個異步運行的ajax,因此您沒有傳統的分步執行方法。 但是,利用$.Deferred API和范圍,您可以克服以下問題:

var rows = '';

// Build your rows
rows += '<tr>...</tr>';

// call ajax method and await successful response
$.ajax({ ... })
  .done(function(data){
    // this is where you compile both tr and data together
  })
  .fail(function(){
    // here all you have is rows since the AJAX call failed
  })
  .always(function(){
    // If you wanted output no matter what, that's what the .always callback is for.
    // It executes after the done/fail callback. So you could populate rows with either
    // the data (done) or a fallback message (fail) then actually output it here.
  });

注意:我不確定您是否打算使用AJAX結果調用Table(data) ,但是如果您打算將其放置在.done()回調中(而不是填充AJAX調用的rows值頭)。

暫無
暫無

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

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