我开始使用移动框架 LungoJS。我和 javascript 不能很好地工作,但我真的想修改这个原始代码:
原始.JS
var mock = function() {
var mock = [];
for (var i=1; i<=5; i++){
mock.push({
id: i,
name: 'name n'+i,
description: 'description n'+i
})
}
lng.View.Template.List.create({
container_id: 'lives',
template_id: 'show_music_template',
data: mock
})
}
return {
mock: mock
}
})(LUNGO, App);
这个原始代码工作正常而且很简单,现在我想使用 $.get 做请求,它返回一个 JSON 文件并像 ORIGINAL.JS 一样填充数组:
JSON 结果:
{"result":[
{"id":"52","username":"jgali","image":"Prova_(live)387.jpeg","name":"Prova (live)","type":"music","language":"Catalan","category":"8","tags":"indie, dine prova, indie live","description":"Aquesta es una prova online de reidiou","licence":"Reidiou License","played":"54","record_time":"45","facebook_id":"1052266203_2342869925158","twitter_hash":"#Provalive","create_date":"2011-11-01 13:04:21"},
{"id":"52","username":"jgali","image":"Prova_(live)387.jpeg","name":"Prova (live)","type":"music","language":"Catalan","category":"8","tags":"indie, dine prova, indie live","description":"Aquesta es una prova online de reidiou","licence":"Reidiou License","played":"54","record_time":"45","facebook_id":"1052266203_2342869925158","twitter_hash":"#Provalive","create_date":"2011-11-01 13:04:21"}
]}
SERVICE.JS
var mock = function() {
var mock = [];
var url = 'http://localhost/app/rest/podcasts';
var data = {};
//lng.Service.get = $get
lng.Service.get(url, data,function(response) {
var array = [];
//Do something with response
jQuery.each(response.result, function() {
mock.push({
id: this.id,
name: this.name,
description: this.description
})
});
document.write(mock[1].id);
});
lng.View.Template.List.create({
container_id: 'lives',
template_id: 'show_music_template',
data: mock
})
}
return {
mock: mock
}
问题是外部循环我不能使用“模拟”数组。当然我犯了几个错误...但是有人知道问题出在哪里吗?
谢谢。
最佳答案
问题是 $.get()
需要时间来执行,因此是异步的。像这样的异步调用涉及使用 callback
函数。要访问 mock
数组,您需要在此回调中嵌套任何内容。
您还可以在 jQuery 中强制 AJAX 调用同步(尽管我和文档对此提出警告);根据 the docs :
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
关于javascript - $.get JSON 请求 + 填充并返回 ARRAY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689644/