如何从匿名成功函数中更新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;
}
Run Code Online (Sandbox Code Playgroud)
cle*_*tus 63
这是错误的做法.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);
Run Code Online (Sandbox Code Playgroud)
Dan*_*n F 14
简短的回答,你不能,AJAX中的第一个A代表异步,这意味着当你到达return语句时请求仍然存在.
您可以使用同步(非异步)请求来执行此操作,但这通常是一件坏事
像下面的oughta返回数据.
function getPrice(productId, storeId) {
var returnHtml = '';
jQuery.ajax({
url: "/includes/unit.jsp?" + params,
async: false,
cache: false,
dataType: "html",
success: function(html){
returnHtml = html;
}
});
return returnHtml;
}
Run Code Online (Sandbox Code Playgroud)
但
除非你真的很需要能够使用从测试的返回值直线距离,你会多更好传递一个回调到测试.就像是
function getPrice(productId, storeId, callback) {
jQuery.ajax({
url: "/includes/unit.jsp?" + params,
async: true,
cache: false,
dataType: "html",
success: function(html){
callback(html);
}
});
}
//the you call it like
getPrice(x,y, function(html) {
// do something with the html
}
Run Code Online (Sandbox Code Playgroud)
编辑 Sheesh,你们快点说出我说的话:-)
nic*_*ckf 12
您的匿名函数确实可以访问returnHtml其范围内的变量,因此其中的代码实际上正如您所期望的那样工作.你可能出错的地方在你的退货声明中.
请记住,一个在AJAX表示asynchronous,这意味着它不会在同一时间发生.出于这个原因,这条线returnHtml = html实际上是在你打电话后发生的return returnHtml;,所以returnHtml仍然是一个空字符串.
很难说你应该做什么来让你的工作按照你想要的方式工作,而不会看到你的其余代码,但你可以做的是为函数添加另一个回调:
function getPrice(productId, storeId, callback) {
jQuery.ajax({
url: "/includes/unit.jsp?" + params,
cache: false,
dataType: "html",
success: callback
});
}
getPrice(5, 1, function(html) {
alert(html);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74067 次 |
| 最近记录: |