[英]Assigning value to a variable from ajax call in ember.js
我試圖用json(從服務器端返回)為變量賦值。 我不想使用ember-data來管理模型和定義RestAdapter,因為它仍處於測試階段。
App.ExamplesRoute = Ember.Route.extend({
beforeModel: function() {
var request = $.post("/Example/GetExamples");
request.then(this.success.bind(this), this.failure.bind(this));
},
success: function(data) {
var examples=data;
alert(example);
if(examples==null){
alert('examples are null');
}
},
failure: function() {
alert('failed');
},
model: function() {
return examples;
}
});
基本上我試圖從json對象為examples變量賦值。 問題是我得到一個javascript錯誤,說明示例未在模型中定義:function(){return examples; }}; 那么這樣做的正確方法是什么?
設置路由的正確方法是這樣的,如果你想在afterModel鈎子中檢查你將要執行此操作的值。
App.ExamplesRoute = Ember.Route.extend({
model: function() {
return $.post("/Example/GetExamples");
}
afterModel: function(model) {
console.log(model);
}
});
我想......
success: function(data) {
var examples=data;
alert(examples);
if(typeof(examples)==='undefined'){
alert('examples are null');
}
},
如果要在成功函數范圍之外訪問它,請添加:
var examples;
在你的函數之上,然后在成功中設置它(不使用var
)。
我同意kingpin2k,但是如果由於某種原因你仍然想要遵循你的路徑,我建議將數據存儲到ember上下文中的變量,就像與你的示例路由相關聯的控制器一樣。
http://emberjs.jsbin.com/OViyEpOd/1/edit
App.ExamplesRoute = Ember.Route.extend({
beforeModel: function() {
var request = $.post("/");/*should use your own url here*/
request.then(this.success.bind(this), this.failure.bind(this));
},
success: function(data) {
//var examples=data;
this.controller.set("examples",data.length);/*or something else useful*/
if(Em.isEmpty(this.controller.get("examples"))){//===null){
alert('examples are null');
}
},
failure: function() {
alert('failed');
}
});
App.ExamplesController = Ember.Controller.extend({
examples:null
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.