我的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);

最佳答案

要设置可观察对象的值,您需要将新值作为第一个参数传入(初始化时为同一广告)。

因此,在回调中,您需要执行以下操作:
    consoleViewModel.currentPlayer(json.player_id);

修改原始对象不会更新currentPlayer的值。

10-04 15:34