无法获取数据,以观察到在淘汰赛js
问题描述:
我发送一个ajax请求来获取数据,与此代码。无法获取数据,以观察到在淘汰赛js
self.emailNotification = ko.observable();
self.checkNotificationOfEmail = function(){
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationOfEmail/' + auth,
contentType: 'application/json; charset=utf-8'
})
.done(function(data) {
alert(data);
self.emailNotification(data.on_off);
})
.fail(function(jqXHR, textStatus, errorThrown) {
self.errorMessage(errorThrown);
})
.always(function(data){
});
};
self.checkNotificationOfEmail();
问题是,当我提醒(数据)我得到的对象物体,当我试图把那个数据,我进入self.emailNotication观察到的,它不工作。不知道我做错了什么。当我尝试提醒self.emailNotification(data.on_off);我弄不明白。 当控制台
答
你的Ajax调用的
检查,你应该使用其他工具比alert
调试,无论是console.log
或最好甚至调试。这会给你加载更多的信息。
您的特定问题可能是由于data
的结构不符合您的预期:它包含数组的项目。除此之外,你的代码很好。请参阅:
var BASEURL = "/testing/", auth = "faketestvalue";
function ViewModel() {
var self = this;
self.emailNotification = ko.observable();
self.checkNotificationOfEmail = function() {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationOfEmail/' + auth,
contentType: 'application/json; charset=utf-8'
})
.done(function(data) {
alert(data);
self.emailNotification(data[0].on_off);
});
};
}
// Fake ajax stuff (synchronously):
var fakeData = [{ on_off: true }];
var $ = {
ajax: function(options) {
return {
done: function(callback) {
callback(fakeData);
}
};
}
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<button data-bind="click: checkNotificationOfEmail">checkNotificationOfEmail</button>
<hr>
Debug info:
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
+0
谢谢,我只是用它,它的工作 –
答
响应是一个数组,所以
self.emailNotification(data.on_off);
是不确定的,你需要访问集合中的第一项
If (data && data.length) {
self.emailNotification(data[0].on_off)
}
+0
感谢您的答案!但是Jaeron在你之前发布了它,所以我想它有权从他第一次以来真正接受他的答案......但是非常感谢! –
有无你尝试使用'console.log()'而不是'alert()'? – cl3m
@ cl3m上传了一张图片 –
响应是一个数组,因此您需要使用data [0] .on_off –