【发布时间】:2012-12-19 19:24:36
【问题描述】:
可能重复:
return from jquery ajax call
jQuery: Return data after ajax call success
$.ajax({
url:"list.php",
dataType: "json",
success: function(resp){
for(var i=0;i<resp.length;i++){
$('#goods_list').append(
"<h3>" + resp[i]["name"] + "</h3>"
+
"<div>Price: NT$" + resp[i]["price"] + "<br />"
+
resp[i]["description"]
+
"<hr /> <a href=# alt='"+ resp[i]["sn"]+ "' class='add_to_cart'>Add</a> | More"
+"</div>"
);
}
var resp2 = resp;
}
});
$('body').append(resp2[0]["price"]);
FireBug 说:
ReferenceError: resp2 is not defined
$('body').append(resp2[0]["price"]);
如何在其他地方使用$.ajax 成功数据? (在 $.ajax 函数之外)
概念类似于“全局变量”。
【问题讨论】:
-
你不能因为请求是异步的(除非你让它同步,这会阻塞你的脚本)。您必须将该行移入成功处理程序。
-
我不完全确定您所追求的模式,但您也可以在函数中返回 ajax 调用,然后在任何地方使用
func().done(...)。
标签: javascript jquery ajax