I am implementing a callback for a 3rdParty javascript library and I need to return the value, but I need to get the value from the server. I need to do something like this:

3rdPartyObject.getCustomValue = function {
   return $.getJSON('myUrl');
}

getJson uses XMLHttpRequest which (I believe) has both synchronous and asynchronous behaviors, can I use the synchronouse behavior?

推荐答案

Looking at the jQuery source code, this is all $.getJSON does:

getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
},

And this is all $.get does:

get: function( url, data, callback, type ) {
    // shift arguments if data argument was omitted
    if ( jQuery.isFunction( data ) ) {
        callback = data;
        data = null;
    }

    return jQuery.ajax({
        type: "GET",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
},

No black magic there. Since you need to customize stuff other than the basic $.getJSON functionality, you can just use the low-level $.ajax function and pass the async option as false:

$.ajax({
    type: 'GET',
    url: 'whatever',
    dataType: 'json',
    success: function() { },
    data: {},
    async: false
});

Json相关问答推荐

震击:三针并用震击

将JSON输入子数组转换为字符串顺序列表输出

由于无效的UTF-8开始字节0xa0,JSON被拒绝,但编码似乎有效

织女星-没有循环的动画条形图第二部分(实际上是织女星)

Jolt规范:将嵌套数组中的null元素移除

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

使用 map_values Select 包含空格的字符串未按预期工作

修改 boost::json::object 中的值

我如何将 JSON 格式与 flutter 一起使用?帮助使用 Gamebanana api

如何使用 React 从 NASA IMAGES API 中解构所需信息

jq搜索特定字符串并输出对应的父值

使用 jq Select 键:值并输出为数组

向 JSON 文件添加注释

使用 boost 属性树读取 int 数组

验证和格式化 JSON 文件

杰克逊:反序列化 for each 值都具有正确类型的 Map

在 React 中访问子级的父级状态

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

运算符不存在:json = json

杰克逊自动将 Joda DateTime 格式化为 ISO 8601 格式