我是一個笨dev的,我努力學習ember.js。Ember.js AJAX模式
我一直在試圖讓一個模型一起,這將使一個AJAX調用服務器,在一個XML文件中提取,分析數據,並將其返回。
以下是我的模型代碼:
App.Statement = Ember.Object.extend();
App.Statement.reopenClass({
all: function() {
var transactions = {};
// FROM: http://jquerybyexample.blogspot.com/2012/04/read-and-process-xml-using-jquery-ajax.html
$.ajax({
type: "GET",
url: "http://www.example.com/transactions.xml",
dataType: "xml",
success: function(xml){
$(xml).find('transaction').each(function(i,v){
transactions[i].id = $(this).attr('id');
transactions[i].vendor = $(this).find('vendor').text();
transactions[i].date = $(this).find('date').text();
transactions[i].spent = $(this).find('spent').text();
});
},
error: function() {
console.log("An error occurred while processing XML file.");
}
});
return transactions;
}
});
下面是我的XML文件(transactions.xml)的內容:
<?xml version="1.0" encoding="UTF-8" ?>
<statement>
<transaction id="123456">
<vendor>WH Smiths</vendor>
<date>2013-05-01</date>
<spent>10.00</spent>
</transaction>
<transaction id="123457">
<vendor>Gap</vendor>
<date>2013-05-02</date>
<spent>39.99</spent>
</transaction>
<transaction id="123458">
<vendor>DSG PLC</vendor>
<date>2013-05-03</date>
<spent>1024.99</spent>
</transaction>
<transaction id="123459">
<vendor>Tesco</vendor>
<date>2013-05-06</date>
<spent>23.35</spent>
</transaction>
</statement>
當我使用控制檯試圖訪問交易對象它仍然未定義任何人都可以指向正確的方向?
UPDATE:
好了,所以基於該回信到目前爲止我的模型現在看起來是這樣的:
var transaction = Ember.ArrayProxy.create({content: []});
App.Statement = DS.Model.extend({
all: function() {
var transactions = {};
// FROM: http://jquerybyexample.blogspot.com/2012/04/read-and-process-xml-using-jquery-ajax.html
$.ajax({
type: "GET",
url: "http://www.atwright.co.uk/cof/statement.xml",
dataType: "xml",
success: function(xml){
var obj = Ember.Object.create({id:null, vendor:null, date:null, spent:null});
obj.setProperties({
id: $(this).attr('id'),
vendor: $(this).find('vendor').text(),
date: $(this).find('date').text(),
spent: $(this).find('spent').text()
});
transaction.pushObject(obj);
},
error: function() {
console.log("An error occurred while processing XML file.");
}
});
return transactions;
}
});
如何訪問任何數據?我可以看到該交易有很多Ember相關的屬性,但沒有數據(儘管我可能會做錯)。
你似乎並不被存儲交易變量的任何地方.. 因爲AJAX請求是異步的,所以你需要將事務存儲在某個地方,這個呃約定是將它們存儲在控制器上的一個'model'變量上。編輯:剛纔看到你在模型內部做AJAX –
我不得不現在暫時擱置 - 所以我會標記一個答案,當我能夠測試等 – atwright147