![](/img/trans.png)
[英]How to set global variables in Javascript/HTML5 in Windows8 store app
[英]How to populate list in windows8 with javascript
我試圖建立一個Windows8應用程序,我使用SplitApp作為基本。 只是嘗試從AJAX添加數據,但失敗。
在文件data.js中,我有:
(function () {
var list = new WinJS.Binding.List();
$.each(data(), function (key, item) {
list.push(item);
});
}
})();
在我擁有的app.js文件中(這有效並填充了應用程序中的列表)
function data() {
var testGroupMeeting = [];
var testMeeting = [];
testGroupMeeting.push(new Group({ id: "1", title: "Group1" }));
testMeeting.push(new Meeting({ group: testGroupMeeting[0], title: "Item Title: 1" }));
return testMeeting;
}
但是,當我想使用AJAX來獲取數據並在填充時返回testMeeting時,它會崩潰。
在文件app.js中,我有(沒有工作),但我需要使它工作
function data() {
var testGroupMeeting = [];
var testMeeting = [];
$.ajax({
url: "/json/json.php",
dataType: 'json',
contentType: 'text/json',
type: 'GET',
success: function (data) {
//Data here is correct and mapped to the arrays, its the same as in the abow example, i have the same data in the arrays as in the above example
}
return testMeeting;
}
});
}
但是問題似乎是AJAX不應該返回任何東西。 而且我無法對data.js進行回調,因為您可以看到該函數是匿名的。
你會怎么做?
因為$ .ajax函數是異步的,所以它不能通過這種方式工作:它執行ajax調用,然后在以后使用適當的數據調用“ success”函數。
您將重寫$ .each(data()...,這樣您就可以調用data並期望它使用testMetting對象調用回調,而不是調用data()並期望它返回testMeeting。
就像是 :
(function () {
var list = new WinJS.Binding.List();
getData(function (theMetting) {
$.each(theMeeting, function (key, item) {
list.push(item);
});
}
})();
// callback is a function that will be called with
// something that is built from the server, after the ajax
// request is done
function getData(callback) {
$.ajax({
// ... everything you did ...
success: function (data) {
// ... use the data to build the meeting object
// and pass it to the callback
callback(meeting)
}
return testMeeting;
}
});
}
同步代碼(返回函數)和異步調用(完成一些工作,然后再調用結果回調)之間存在根本區別。 $ .ajax是典型的異步函數。
從理論上講,您可以將“ async”標志傳遞給ajax,以便$ .ajax函數在Ajax調用完成之前不會返回,但是您可能不想這樣做,因為它會阻塞您的UI。
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.