[英]How to get value of async JSONP request?
I need to receive a value of JSONP async request. 我需要接收JSONP异步请求的值。 When I assigning "data" to global variable, I receive a empty object.
将“数据”分配给全局变量时,会收到一个空对象。 Please, help me.
请帮我。
Now, I my code get 现在,我的代码得到了
var url = "http://local/main/getEventData/" + event_id;
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
var event_data = {};
function callback(data) {
event_data = data;
}
and JSONP 和JSONP
callback({name: 'John'})
PS Request absolutely works and I can display data variable via console.log(data) PS请求绝对有效,我可以通过console.log(data)显示数据变量
Use the data when you get it, not (as I assume you are trying now) as soon as you're requested it. 在获取数据时立即使用数据,而不是(在我认为您正在尝试的情况下)在收到请求后立即使用。
function callback(data) {
event_data = data;
// Now you have the data, do something with it.
}
// Don't try to use event_data here. There's no way
// to know if the callback has fired yet
What you've got will work just fine. 您所拥有的将正常工作。 You'll just have to put the code (or a call to a function, or whatever) inside your "callback" function so that the code doesn't run until the script is retrieved.
您只需要将代码(或对函数的调用等) 放入 “回调”函数中,以使代码在检索脚本之前不会运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.