如何读取 jQuery $.get 方法返回的对象
我想知道如何通过 jQuery 的 $.get() 方法从返回的对象中提取数据。 IE:
function dynamicData(file){
var wantedData;
var getObj = $.get(file);
wantedData = getObj.complete(function(data){return data;});
return wantedData;
}
$(window).load(function(){
var newData = dynamicData('somefile');
alert(newData);
});
我不想在获得新数据后立即将数据粘贴到某个 DOM 上。
我收到一个对象警报,但如何获取其中的数据?我不知道此时对象结构如何,因为 newData 是一个对象,但 newData[0] 为空。这是偶然的某种带有键:值对的映射对象吗?或者我们不允许这样做?
I was wondering how to extract data from a returned object via jQuery's $.get() method. IE:
function dynamicData(file){
var wantedData;
var getObj = $.get(file);
wantedData = getObj.complete(function(data){return data;});
return wantedData;
}
$(window).load(function(){
var newData = dynamicData('somefile');
alert(newData);
});
I don't want to just stick the data to some DOM as soon as it's gotten the new data.
I get an object alerted, but how do I get data inside of it? I have no idea how the object structure is at this point since newData is an object, but newData[0] is null. Is this by chance some sort of mapped object with key:value pairs? or are we not allowed to do it this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法从 Ajax 调用返回。它是异步的。
对成功回调中的数据执行任何您想要执行的操作。
请参阅 get 手册,其中有示例。
You can't return from an Ajax call. It's Asynchronous.
Do whatever you want to do with the data in the success callback.
See the manual for get, which has examples.
由于 $.get() 是异步的,因此您在 get 返回任何数据之前调用警报。
更好的方法是:
当数据可用时会发出警报。
Since $.get() is asynchronous, you're calling your alert before the get returns any data.
A better approach would be:
which will alert(data) when it becomes available.
$.get 需要一个回调函数,该函数将在加载完成后立即接收数据。它不会直接将数据返回给调用函数!
请参阅 jQuery.get 文档 了解更多信息。
$.get requires a callback function that will receive the data as soon as it is done loading. It will not directly return the data to the calling function!
Please refer to the jQuery.get documentation for more information.