0

这是一个非常简单的问题,所以请不要开玩笑......我已经获得了一个 Web 服务的 URL,它将为我提供一个 JSON 对象。我希望使用 jQuery 的 getJSON 方法,例如...

var myObj = $.getJSON("https://www.myurl/");

但是,这不起作用,因为当我使用 console.log(myObj.toSource()) 时,我似乎在将 JavaScript 写入控制台而不是我的对象时得到了很多。我知道我可以用这个方法添加一个回调,我应该这样做:

var thisJsonObj;

$.getJSON("https://www.myurl/", function(result){
    thisJsonObj = result;

});

console.log(thisJsonObj.toSource());

这也不起作用......我哪里出错了?该 URL 有效且正确。

4

2 回答 2

2

Ajax 以异步方式工作,因此您必须在回调函数中使用 JSON 对象:

var thisJsonObj;
$.getJSON("https://www.myurl/", function(result) {
    thisJsonObj = result;
    console.log(thisJsonObj);
});

此外,如果您使用外部 web 服务,您应该考虑将请求视为JSONP。因此,请检查您的 URL 是否有点像“callback=?”。

于 2012-05-11T12:15:34.397 回答
0

虽然 URL 可能是 Web 服务的 URL,但您是否假设在 Web 服务中调用函数?例如,如果您有一个 python 微框架(例如我的示例中的Flask),并且我想获取要在组合框中显示的项目列表,那么我的 python 可能看起来有点像:

@app.route('/_gest_list.json')
def get_list():
    #return list of jsonified items

在你的 jQuery 中调用

$.getJSON("/get_list.json", {}, function(data) {
    //Do something
});

把它想象成我正在调用get_list()映射到 webservice/server 的 url 并具有别名的函数/get_list.json

Also if you are working with ASP.Net to access the data you must write something like (variable name).d. All JSON data in ASP.Net is wrapped within d!

于 2012-05-11T12:45:00.047 回答