getJSON不支持async:false [英] getJSON does not honor async:false

查看:146
本文介绍了getJSON不支持async:false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有这段代码,应该可以返回调用结果.我需要同步执行此操作,以便我知道一切都很好,但是它似乎不起作用.我在做什么错了?

I have this code below, which is supposed to return the result of the call. I need to do this synchronously so that I know everything is good, however it doesn't seem to work. What am I doing wrong?

/* jQuery library:
 * http://code.jquery.com/jquery-1.9.1.min.js
 */
function getJSON(url){
    var result;
    $.getJSON(url, { async: false, success: function(data) {
        result = data;
        alert(data); // **Edit**: also undefined
    }});
    alert(result); // undefined
    return result;
}

推荐答案

getJSON不支持async:false

getJSON does not honor async:false

getJSON 没有选项.为此,您必须使用 ajax .

getJSON has no async: false option. You'd have to use ajax for that.

根据文档,getJSON等效于:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

...,您可以在其中轻松添加async: false选项(目前,请注意,jQuery将放弃对此的支持).

...to which you can easily add an async: false option (for now, be forewarned that jQuery will be dropping support for that).

我需要同步执行此操作,以便我知道一切都很好

I need to do this synchronously so that I know everything is good

您不需要同步执行任何操作来知道一切都很好",完全有可能(而且是正常的)异步处理结果(无论是好"还是错误).

You don't need to do anything synchronously to "know everything is good", it's perfectly possible (and normal) to handle results (whether "good" or errors) asynchronously.

在对您的问题的评论中,您写道:

In the comments on your question, you've written:

jsonp?这是我正在使用的代码.

jsonp? This is the code I am using.

JSON-P JSON (并且getJSON不会执行JSON-P,除非您的URL中具有callback=?或类似名称),并且JSON-P是内在异步的.与通过XMLHttpRequest进行真正的ajax调用不同,不可能使JSON-P同步.

JSON-P is not the same as JSON (and getJSON doesn't do JSON-P unless you have callback=? or similar in the URL), and JSON-P is inherently asynchronous. Unlike a true ajax call via XMLHttpRequest, it's impossible to make JSON-P synchronous.

这篇关于getJSON不支持async:false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆