我遇到了使用knockout.js綁定json響應的問題。任何人都可以幫助我指出正確的方向嗎?下面有兩個版本的代碼。版本1正在工作,但用戶需要搜索。如果他們搜索不止一次,就會因爲已經應用了綁定而中斷。從ajax JSON響應在Knockout.Js中綁定關聯數組
版本1
var self = this;
self.Jobs = ko.observableArray();
self.Count = ko.observable();
self.Score = ko.observable();
self.Highlights = ko.observable();
self.Document = ko.observableArray();
self.id = ko.observable();
self.title = ko.observable();
self.description = ko.observable();
self.company = ko.observable();
self.error = ko.observable();
var jobsUri = '/home/search/';
function getAllJobs() {
var search = $('#search').val();
$.post(jobsUri, {
search: search
},
function (data) {
viewModel = {
Jobs: data.Results,
Count: data.Count,
Document: Jobs.Document,
id: Document.id,
title: Document.title,
description: Document.description,
company: Document.company
}
ko.applyBindings(viewModel, $('#jobs').get(0));
});
}
2版似乎工作和元素出現在DOM,但由於某種原因,我似乎並沒有能夠與淘汰賽訪問的元素顯示在前端。
2版
function ViewModel() {
var self = this;
self.data = ko.observableArray();
getAllJobs();
}
function getAllJobs() {
var self = this;
self.Jobs = ko.observableArray([]);
self.Count = ko.observable();
self.Score = ko.observable();
self.Highlights = ko.observable();
self.Document = ko.observableArray();
self.id = ko.observable();
self.title = ko.observable();
self.description = ko.observable();
self.company = ko.observable();
self.error = ko.observable();
var jobsUri = '/home/search/';
var search = $('#search').val();
$.post(jobsUri, {
search: search
},
function (data) {
viewModel = {
Jobs: data.Results,
Count: data.Count,
Document: Jobs.Document,
id: Document.id,
title: Document.title,
description: Document.description,
company: Document.company,
}
});
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
的HTML是非常基本的。如上所述,它適用於上面的版本1代碼,但不適用於版本2!
<div class="row" id="jobs search">
<input type="text" id="search" class="form-control" value="" placeholder='"Senior Manager" "Corporate Finance" London "Investment Banking"' />
<input type="submit" class="typeahead search-submit btn btn-success btn-block " value="Search" onclick="getAllJobs();" />
<hr />
<div data-bind="foreach: Jobs">
<div class="jobs-list">
<h3 class="job-title" data-bind="text: Document.title"></h3>
<p data-bind="text: Document.company"></p>
<p data-bind="text: Document.description"></p>
</div>
</div>
</div>
我覺得我已經嘗試了一切可能,但只是沒有破解它!任何幫助不勝感激。在此先感謝
非常感謝。今天早上我纔開始打淘汰賽。現在你已經指出了我正確的方向,這很有道理。 Muchos Gracias。 :) –
沒問題,不客氣。對於下一個問題:請壓縮您的代碼示例,與我在答案中做的相似。儘量消除任何不直接導致問題的複雜性。您的讀者以及該線程的任何未來訪問者都將感謝您提供一個點點,無雜亂的問題。 – Tomalak