jQuery:将 Ajax 获取到变量?
我认为下面显示的代码可以发挥作用,但显然事实并非如此。我不知道为什么它不起作用 - URL 已正确获取(使用 firebug 检查),但它拒绝将结果保存到我的变量(globalVar)中。
我能做些什么?
var globalVar;
function fetchDataset(kategori){
$.getJSON(apiUrl + "?jsoncallback=?", function(json){
globalVar = json;
console.log(globalVar); // Returns Undefined!
});
}
I thought that the below shown code would work as a charm, but apparently it doesn't. I can't tell why it isnt working - The URL is fetched properly (checked with firebug) but it refuses to save the result to my variable (globalVar).
What can I do?
var globalVar;
function fetchDataset(kategori){
$.getJSON(apiUrl + "?jsoncallback=?", function(json){
globalVar = json;
console.log(globalVar); // Returns Undefined!
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想萤火虫应该显示你的回调的内容。我有一个类似的问题并使用 .parseJSON(); 解决了它
http://api.jquery.com/jQuery.parseJSON/
也许有帮助。
回调的 json 格式是否整齐/“正确”?
I guess firebug should display the contents of your callback. I had a similar problem and solved it using .parseJSON();
http://api.jquery.com/jQuery.parseJSON/
Maybe it helps.
Is the callback neatly formatted/"correct" json?
您的变量不是全局的。您在函数的范围内定义了它。您的 Ajax 调用是异步运行的,这意味着您的函数将(可能)在 ajax 请求返回之前完成。尝试在函数外部声明 globalVar。 IE。
编辑:此外,检查
statusText
(传递给回调函数的第二个变量)以确保您的请求没有错误。Your variable is not global. You defined it within the scope of the function. Your Ajax call is run asynchronously which means that your function will complete (probably) before the ajax request is returned. Try declaring globalVar outside of the function. ie.
Edit: Also, check the
statusText
(second variable passed to the callback function) to make sure that there are no errors with your request.您是否正在发出跨域请求?
如果是这样,请确保您使用 jsonp
这里有一个 jsonp 的例子。
http://api.jquery.com/jQuery.getJSON/
Are you making a cross domain request?
If so make sure you use jsonp
There is an example here of jsonp.
http://api.jquery.com/jQuery.getJSON/
显然,没有任何效果,所以我最终制作了一个基于 PHP 的代理来传输任何跨域请求。将 url 更改为 PHP 代理后,效果很好。
感谢大家的帮助。非常感谢!
Apparently, nothing worked, so I instead ending up making a PHP-based proxy that tunnels any cross-domain request. After changing the url to the PHP proxy, it worked great.
Thanks for everyones help. Very appreciated!