2010-03-30 50 views
1

我想使用下面的代碼執行嵌套的AJAX調用。嵌套調用似乎不起作用。我做錯了什麼?JQuery - 嵌套AJAX

$.ajax({ 
type: 'GET', 
url: "/public/customcontroller/dosomething", 
cache: false, 
dataType: "html", 
success: function(html_input) 
{ 
    $.ajax({ 
     type: 'GET', 
     url: "/public/customcontroller/getjobstatus", 
     cache: false, 
     dataType: "html", 
     success: function(html_input){ 
     alert(html_input); 
     } 
    });                  
} 
}); 
+0

取決於,是第一次通話成功嗎?否則'success'中的函數永遠不會被調用。 – 2010-03-30 19:58:11

+0

我會在內部函數中調用'html_input'不同的東西 – 2010-03-30 19:59:47

+0

第一次調用成功。我在內部函數中將html_input重命名爲html_response ..仍然沒有運氣.. – Jake 2010-03-30 20:04:29

回答

5

你可以考慮到外呼是異步的,可以走出去的範圍的成功處理程序才能發揮作用是具有螺紋型的問題。嘗試將成功召集到一個單獨的功能中。

+0

很想看到一個例子。 – atwellpub 2014-01-24 03:27:13

+0

爲什麼這是被接受的答案? – 2016-08-01 20:41:24

3

試試這個

$.ajax({ 
type: 'GET', 
url: "/public/customcontroller/dosomething", 
cache: false, 
dataType: "html", 
async: false, 
success: function(html_input) 
{ 
    $.ajax({ 
     type: 'GET', 
     url: "/public/customcontroller/getjobstatus", 
     cache: false, 
     dataType: "html", 
     success: function(html_input){ 
     alert(html_input); 
     } 
    });                  
} 
}); 
+0

:在上面的代碼中,而不是「dataType」,你應該使用「數據類型」。 – 2013-10-31 09:28:26

+0

@suraj http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings指出該選項名爲dataType。 – Ben 2013-10-31 15:50:07

0

使用async/await語法。

async function foo() { 
    var html_input = await $.ajax({ 
     type: 'GET', 
     url: "/public/customcontroller/dosomething", 
     cache: false, 
     dataType: "html" 
    }) 

    var html_input2 = await $.ajax({ 
     type: 'GET', 
     url: "/public/customcontroller/getjobstatus", 
     cache: false, 
     dataType: "html" 
    }) 

    alert(html_input2) 
} 
foo().catch(e => console.log('some error:', e))