我的html在页面初始化时显示“占位符”,但是我的ajax调用没有更新。是否存在某种范围问题?
var currentPlayer = {
"player_id": "placeholder"
};
$.ajax({
url: "/players/summary",
success: function(json) {
// when this ajax call is completed the placeholder string is not replaced by
// currentPlayer.player_id. I have verified that the currentPlayer hash does
// have that value after this ajax call
currentPlayer = json;
}
});
var dashboardViewModel = {
// <span data-bind="text:currentPlayer"></span> displays the "placeholder"
// string upon initialization
currentPlayer: ko.observable(currentPlayer.player_id),
vsPlayer: ko.observable("VS: ALL PLAYERS")
};
ko.applyBindings(dashboardViewModel);
编辑:
这就是我解决问题的方法:
var dashboardViewModel = {
currentPlayer: ko.observable({"player_id": ""}),
vsPlayer: ko.observable("VS: ALL PLAYERS")
};
ko.applyBindings(dashboardViewModel);
$.get("/players/summary", dashboardViewModel.currentPlayer);
答案 0 :(得分:3)
要设置observable的值,您需要将新值作为第一个参数传递(初始化时使用相同的广告)。
所以,在你的回调中,你会想要这样的东西: dashboardViewModel.currentPlayer(json.player_id);
修改原始对象不会更新currentPlayer的值。