如何从匿名成功函数中更新returnHtml变量?
function getPrice(productId, storeId) { var returnHtml = ''; jQuery.ajax({ url: "/includes/unit.jsp?" + params, cache: false, dataType: "html", success: function(html){ returnHtml = html; } }); return returnHtml; }
那是错误的方法。AJAX中的第一个A是异步的。该函数在AJAX调用返回之前返回(或者至少可以返回)。因此,这不是范围问题。这是订购的问题。只有两个选项:
async: false
作为(2)的示例:
function findPrice(productId, storeId, callback) { jQuery.ajax({ url: "/includes/unit.jsp?" + params, cache: false, dataType: "html", success: function(html) { // Invoke the callback function, passing the html callback(productId, storeId, html); } }); // Let the program continue while the html is fetched asynchronously } function receivePrice(productId, storeId, html) { // Now do something with the returned html alert("Product " + productId + " for storeId " + storeId + " received HTML " + html); } findPrice(23, 334, receivePrice);