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?

推荐答案

看看jQuery的源代码,这就是$.getJSON个功能:

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

这就是$.get所做的一切:

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字符串处理注入引号

使用Jolt v.0.1.1向每个json元素添加一个键-值对

JSON API返回多个数组,需要帮助拼合数据以存储在SQL Server数据库表中

褐煤面积图中的分选问题

序列化从/到空值

如何在JSONata对象中迭代并向数组添加新字段?

震动范围改善

从 oracle 数据库中的 json blob 打印值

如何在 JSonPath 中按值查找列表中的所有元素

将=分隔值文件转换为:json文件

使用 KQL 和外部 data() 运算符从 json 文件中提取信息

在 rust 中从 API 反序列化 serde_json

PowerShell - JSON/PsCustomObject - 为什么我的数组被扁平化为一个对象?

无法向 Json 数组添加新元素

N1QL 聚合查询 Couchbase

从多维数组数据生成json字符串

将字符串映射到json对象的多种类型?

获取一个数字的 PHP 对象属性

确保数组中的项目属性在 Json Schema 中是唯一的?

如果键可能不存在,则从 Python dict 读取