gpt4 book ai didi

javascript - 使用 Knockout Js 进行 Ajax 数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-01 02:18:18 26 4
gpt4 key购买 nike

我正在使用knockout js,我发现在ajax get方法中绑定(bind)数据很困难,我已经创建了模型,viewModel和ajax函数,我在同一个中具有ajax方法在我创建 viewModel 的 js 文件中,我在页面加载时调用 ajax 并尝试将我的 html 与 konckout js 绑定(bind),如果我给出 this.name = ,我会收到错误 userModel is undefined ko.observale(result[0].name) 在ajax调用之前,在ajax调用之后给出名称未定义需要帮助

<html>
<head>
<script src="js/jquery1.9.js"></script>
<script src="js/knockout-3.3.0.js"></script>
<script src="js/knockout.mapping.js"></script>
<script src="model/usermodel.js"></script>
</head>

<body>

<div>
<h1><span data-bind="text:user().name"></span></h1>
<h1><span data-bind="text:user().userName"></span></h1>
</div>
<script src="ViewModel/userDetailsViewModel.js"></script>
</body>
</html>
////Model////
function userModel(result) {
var self = this;
this.name = ko.observable(result[0].name); /// give me error undefined before the ajax call and after ajax call i get the value in result
this.userName = ko.observable();

}

/////View Model////
var result
var userDetailsViewModel = function(result) {
self = this;
self.user = ko.observable(new userModel(result));
};
var mainUserDetailsViewModel = new userDetailsViewModel(result);
ko.applyBindings(mainUserDetailsViewModel);

////ajax called on the page load ////
$.ajax({
type: "POST",
dataType: "json",
url: baseUrl + 'api/xx/xxx',
data: jason.strigfy(),
success: function(data) {
result = data;
////I am getting in result json data object 0=["name":"nnnn","Username":"mmmmmm"],
//// i am passing this result to ViewModel and to Usermodel Constructor//
mainUserDetailsViewModel.user(new userModel(result));

},
error: function(error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});

最佳答案

这是我的建议,即拥有一个干净的嵌套 View 模型。
示例:https://jsfiddle.net/kyr6w2x3/28/

function UserViewModel() {
var self = this;
self.UsersList = ko.observableArray([]);

self.GetUsers = function() {
$.ajax({
type: "POST",
dataType: "json",
url: baseUrl + 'api/xx/xxx',
data: jason.strigfy(),
success: function (data) {
//Here you map and create a new instance of userDetailVM
self.UsersList($.map(data, function (user) {
return new UserDetailViewModel(user);
}));
}
});
}
//call to get users list when the VM is loading or you can call it on any event on your model
self.GetUsers();
}
function UserDetailViewModel(data){
var self = this;
self.Name = ko.observable(data.name);
self.UserName = ko.observable(data.username);
}

ko.applyBindings(new UserViewModel());

查看:

 <h1 data-bind="foreach: UsersList">
<div data-bind="text: Name"></div>
<div data-bind="text: UserName"></div>
</h1>

关于javascript - 使用 Knockout Js 进行 Ajax 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com