2013-05-07 23 views
1
function pdfToImgExec(file, IsfirstLogging, folder, round) { 
    alert(file); 
    var postString = file + '&' + IsfirstLogging + '&' + folder + '&' + round; 
    var errorMsg = (folder == 'Incoming' ? '<p>error in incoming folder</p>' : '<p>error in other folder</p>'); 
    $.ajax({ 
    type: "POST", 
    cache: false, 
    async: false, 
    url: "pdfToImgExec.php", 
    data: { 
     "data": postString 
    }, 
    dataType: "html", 
    beforeSend: function() { 
     alert(file + 'a'); 
     $('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>'); 
    }, 
    success: function (data) { 
     if(data == '1') { 
     $('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>'); 
     } else if(round < 4) { 
     $('#pdfToImgResult').html('<p>Fail to convert , retry ' + round + ' round <img src="loading.gif" height="20" width="20"/></p>'); 
     round++; 
     pdfToImgExec(file, 'false', folder, round); 
     } else { 
     folder == 'Incoming' ? tempFailIncomingFiles.push(file) : tempFailResultFiles.push(file); 
     } 
    }, 
    error: function (x, t, m) { 
     $('#pdfToImgResult').html(errorMsg); 
     alert(t); 
     releaseBtn(); 
    } 
    }); 
} 

這個Ajax調用的問題是,我可以提醒(文件+「A」)在beforeSend功能,但爲什麼Ajax調用之前的文本不顯示?

$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>'); 

不能正常工作,它不會顯示任何東西,但只躍升至在ajax調用完成後,

$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>'); 

是否歸功於async:false?如何解決這個問題?謝謝。

回答

1

這是因爲您使用的是async: false,,所以該功能會阻塞,直到請求完成,阻止重繪,直到完成所有操作。

你似乎都設置了回調,所以似乎沒有任何理由做出阻塞的xhr請求。只要刪除async: false,,你應該全部設置。


下面是如何處理異步代碼的一個簡單示例。我已經刪除了大部分代碼以保持簡短。

// --------------------------------new parameter-------------v 
function pdfToImgExec(file, IsfirstLogging, folder, round, callback) { 
    // your code... 
    $.ajax({ 
    type: "POST", 
    cache: false, 
// async: false, // Remove this line! 
    url: "pdfToImgExec.php", 
    data: { 
     "data": postString 
    }, 
    dataType: "html", 
    beforeSend: function() { 
     $('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>'); 
    }, 
    success: function (data) { 
     // your code... 

     // Invoke the callback, passing it the data if needed 
     callback(data) 
    }, 
    error: function (x, t, m) { 
     // your code; 
    } 
    }); 
} 

當你調用pdftoImgExec,傳遞函數爲響應完成時將調用的最後一個參數。該功能是您的代碼恢復的地方。

pdfToImgExec(..., ..., ..., ..., function(data) { 
    // resume your code here. 
    alert(data); 
}) 
+0

thx回答,我已經把display語句放在beforeSend函數中,並且我試過了alert alert,它正在工作。只有改變html元素的語句不起作用 – user782104 2013-05-07 01:35:20

+0

@ user782104:'alert()'不需要重畫頁面以顯示。更新元素的'.html()'內容。您正在阻止重繪,直到該功能完成。 – 2013-05-07 01:36:31

+0

async:false是需要維護程序的順序..爲什麼它阻止html(),因爲我已經把它放在BeforeSend中了? – user782104 2013-05-07 01:36:32

相關問題