那是错误的方法。AJAX中的第一个A是异步的。该函数在AJAX调用返回之前返回(或者至少可以返回)。因此,这不是范围问题。这是订购的问题。只有两个选项:
- 使用选项使AJAX调用同步( 不推荐 )
async: false
;要么 - 改变思维方式。代替从函数返回HTML,您需要传递一个回调,以在AJAX调用成功时被调用。
作为(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);


