jquery 异步和 JSON 数据
继 javascript jquery 并使用 eval 之后,我仍然无法让 jquery 异步读取数据。
data1=[1,2,3,4]
注意:我在下面的示例中包含了 async:true 只是为了显示差异
下面的示例返回“null”
$(document).ready(function(){
var myArray=[];
myArray=getValues();
alert(myArray);
function getValues(){
var result=null;
$.ajax({
url: 'data1.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;},
async:true,
});
return result;
};
})
,下面的示例工作正常并在数组中给出结果,即 [1,2,3,4]
$(document).ready(function(){
var myArray=[];
myArray=getValues();
alert(myArray);
function getValues(){
var result=null;
$.ajax({
url: 'data1.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;},
async:false,
});
return result;
};
})
有人可以解释一下如何异步获取结果 谢谢
following from javascript jquery and using eval i still could not get jquery to read the data asynchronously.
data1=[1,2,3,4]
Note: i have included async:true in the below example just to show the difference
Below example return "null"
$(document).ready(function(){
var myArray=[];
myArray=getValues();
alert(myArray);
function getValues(){
var result=null;
$.ajax({
url: 'data1.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;},
async:true,
});
return result;
};
})
and below example work fine and gives the result in an array i.e [1,2,3,4]
$(document).ready(function(){
var myArray=[];
myArray=getValues();
alert(myArray);
function getValues(){
var result=null;
$.ajax({
url: 'data1.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;},
async:false,
});
return result;
};
})
can someone explain how to get the results asynchronously
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会把它改成这样...
I would change it to this ...
这应该有效,因为它在我身上有效,但我建议你不要这样做。
This should work, as it has worked in mine, but i suggest you not to do it.
第一部分,结果异步返回到 myArray,但在此之前,alert 函数已经执行,因为 ajax 是异步发生的。因此,如果您在“返回结果”之后立即发出警报,您应该会看到结果。
first part, the result is returned asynchronously to myArray, but before that, the alert function has already executed because the ajax happened asynchronously. So if you place alert right after "return result", you should see the result.
默认情况下,所有请求均
异步发送
。默认情况下
true
。如果您需要同步请求,请将此选项设置为
false
。跨域
请求和dataType: "jsonp"
请求不支持同步操作。请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作。如果您需要确保该方法始终显示最新数据,请使用
cache:false
和async:false
。另外,为了避免超时/错误,请使用success
/error
/complete
回调选项。By default, all requests are sent
asynchronously
.true
by default.If you need synchronous requests, set this option to
false
.Cross-domain
requests anddataType: "jsonp"
requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.If you need to ensure that the method always displays the latest data then use
cache:false
andasync:false
. Also to avoid timeout/error usesuccess
/error
/complete
callback options.