2013-10-14 23 views
1

你好,我對這個論點很困惑:我知道在JavaScript函數有時以異步方式執行 ,這是我的問題。我有一個函數叫做功能和防禦jquery

function createPopupHour() 

這個函數創建一個html select元素,它不會返回任何東西。我在請求成功部分的$ .AJAX請求中調用了這個函數。

$.ajax({ 
      url:"responseregistrodocente.php", 
      data:{ 
       operazione:'caricaAssenza', 
       idAssenza:id_array[3], 
       codiceFiscale: id_array[0], 
       data:id_array[1], 
       tipo:id_array[2] 
       }, 
      type:"POST", 
      dataType:"json", 
      success: function (jsonObject) { 
      createPopupHourSelect() 
      //other code 
      }); 

      }, 
      error: function(error){ 
       //XMLREQQUESTOBJECT 
       alert(error.responseText); 
       location.reload(); 
      }, 
      cache:false, 
      ifModified:false 
     }); 

的問題是,當我調用函數的其他代碼不衡量某人,我的功能結束。我知道在jQuery中有「延期對象」,也許我需要我的函數創建一個延期對象,並將其返回給代碼。但是sintax怎麼樣?還是有另一種更容易和乾燥的解決方案?

是這樣的嗎?

function createPopupHour select(){ //staff to do 
return $.deferred();//it's in pending state 
} 

,並執行$就

$.ajax({ 
       url:"responseregistrodocente.php", 
       data:{ 
        operazione:'caricaAssenza', 
        idAssenza:id_array[3], 
        codiceFiscale: id_array[0], 
        data:id_array[1], 
        tipo:id_array[2] 
        }, 
       type:"POST", 
       dataType:"json", 
       success: function (jsonObject) { 
       var defered=createPopupHourSelect() 
       defered.then(function{//other code]) 
         defered.resolve(); 
       }); 

       }, 
       error: function(error){ 
        //XMLREQQUESTOBJECT 
        alert(error.responseText); 
        location.reload(); 
       }, 
       cache:false, 
       ifModified:false 
      }); 
+0

你是什麼意思的「其他代碼不知道我的函數結束」? – Johan

+0

當函數在執行調用後返回代碼時,正常程序流程不需要使用異步代碼。如果其他代碼沒有運行,那麼這可能是因爲你的代碼在調用函數時或者在函數內部崩潰了。檢查錯誤控制檯是否有任何Javascript錯誤消息。 – Guffa

+0

我的意思是代碼必須運行之前,功能beacuse我不能例如更改一個按鈕的css風格比我在函數中創建,因爲當css被修改時,按鈕不存在。 –

回答

1

是的,other code需要居住在彈出時的事情是完成將要執行的回調函數,就像在彈出的啓動代碼當AJAX已經完成了。您可以使用原始回調,也可以使用更強大的promise模式。

jQuery Deferred objects的語法是

function …() { 
    var def = $.Deferred(); 
    // start asynchronous task 
     // when the task is done (in the future), call 
     def.resolve(…); // optionally with results 
    // and right now do 
    return def.promise(); 
} 

由於$.ajax不會返回一個承諾爲好,則可以通過.then使用鏈接(假設createPopUpHourSelect是在上述圖案):

$.ajax({ 
    url:"responseregistrodocente.php", 
    data:{…}, 
    type:"POST", 
    dataType:"json", 
    cache:false, 
    ifModified:false 
}) 
.fail(function(error){ 
    alert(error.responseText); 
    location.reload(); 
}) 
.then(createPopupHourSelect) // gets passed the parsed JSON 
.then(function(result) { // gets passed the resolve arguments from the popup 
    // other code 
}); 

如果您還需要其他代碼中的ajax響應,並且不想通過彈出功能傳遞它,請使用

.then(function(json) { 
    return createPopupHourSelect(…) 
    .then(function(popupResults) { 
     // other code 
    }); 
}) /* returns a promise that resolves with result of other code 
.then(…) */