2016-02-26 122 views
-1

对于某些需要使用Ajax同步的业务,有人可以帮助我如何使用,我发现了一些类似的代码,但不明白它的作用。在Ajax请求中使用同步

function getData(productId, storeId) { 
    var returnHtml = ''; 

    jQuery.ajax({ 
    url: "/includes/unit.jsp?" + params, 
    async: false, 
    cache: false, 
    dataType: "html", 
    success: function(html){ 
     returnHtml = html; 
    } 
    }); 

    return returnHtml; 
} 
+1

同步Ajax是一件很可怕的事情。相反,您应该编写代码以异步使用Ajax结果。一旦你学会了如何去做,代码并不难。您只需在回调中使用Ajax结果,而不是在函数返回中使用。仅供参考,“Ajax”中的“A”代表“异步”。 – jfriend00

+0

'async:false'已弃用。浏览器专门*不*希望你这样做。你为什么认为你需要?你试图解决的实际问题是什么? – David

+0

请参阅http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call以了解如何使用异步方法,而不是试图使用弃用的同步AJAX。 – Barmar

回答

0

您的代码是标准jQuery ajax代码,async属性设置为false。这迫使ajax调用是同步的。

function getData(productId, storeId) { 
    var returnHtml = ''; 

    jQuery.ajax({ 
    url: "/includes/unit.jsp?" + params, 
    async: false, // <-- this forces the ajax call to be synchronous. 
    cache: false, 
    dataType: "html", 
    success: function(html){ //<<-- This is where you get the ajax response 
     returnHtml = html; 
    } 
    }); 

    return returnHtml; 
} 

请注意,同步ajax调用不是很高效。