2012-05-21 199 views
-1

函數觸發數據庫調用,它返回一些JSON。然後使用此CID來標記新添加的DOM元素。的JavaScript函數返回值範圍

我需要檢索/恢復「CID」阿賈克斯成功區塊內它存在的價值,它將被用來更新屬性。由於AJAX是異步完成的(因此在AJAX的a),你的函數返回的AJAX調用完成之前

錯誤 CID沒有被定義

//Save New Task 
$("body").on('click','.icon-facetime-video',function(event){ 
    var new_entry = $(this).prev().val(); 
    var thebid = $(this).parents('tbody').prev().find('th').attr('id').split('_')[1]; 
    $(this).parent().addClass('tk').html('<i class="icon-eye-open"></i> '+new_entry); 
    //CALL FUNCTION 
    var cid = update_entry('new_tk',new_entry,thebid); //value of cid from update_entry 
    $(this).parent().attr('id','cid_'+cid); 
}); 

function update_entry(typeofupdate,new_entry,thebid){ 

    switch(typeofupdate){ 
    case 'new_tk': var action = 'new_tk'; 
    break; 
    } 

    $.ajax({ 
     type:'post', 
     url: 'posts_in.php', 
     dataType: "json", 
     data: {cid : thebid, action: action, content: new_entry}, 
     success: function(data){ 
      var action = data[0],cid= data[1]; 
      console.dir(data); 
     } 
    }); 

    return cid; 
} 
+2

Ajax調用不同步,所以你前人的精力等到它返回的值。呦可能還想在這個調用中寫一個'error:function()'以防萬一。的 – inhan

+2

可能重複[我怎樣才能從一個AJAX請求返回的值?(http://stackoverflow.com/questions/2956261/how-can-i-return-a-value-from-an-ajax-request) [從嵌套異步AJAX調用返回的結果]的 – Phrogz

+1

可能重複(http://stackoverflow.com/questions/10189367/return-result-from-nested-asynchronous-ajax-call) – Quentin

回答

2

。你應該通過一個回調函數到update_entry,並在你的AJAX成功處理程序運行:

var self = this; 

update_entry('new_tk', new_entry, thebid, function(cid) { 
    $(self).parent().attr('id', 'cid_' + cid); 
}); 

function update_entry(typeofupdate, new_entry, thebid, callback) { 

    switch(typeofupdate){ 
    case 'new_tk': var action = 'new_tk'; 
    break; 
    } 

    $.ajax({ 
     type:'post', 
     url: 'posts_in.php', 
     dataType: "json", 
     data: {cid : thebid, action: action, content: new_entry}, 
     success: function(data){ 
      var action = data[0], cid= data[1]; 
      callback(cid); 
      console.dir(data); 
     } 
    }); 
} 
+0

非常感謝約瑟夫,這非常有幫助。 :) – Codex73