knockout.js
AJAXリクエストとバインディング
サーチ…
バインディング付きサンプルAJAXリクエスト
Page.html
<div data-bind="foreach: blogs">
<br />
<span data-bind="text: entryPostedDate"></span>
<br />
<h3>
<a data-bind="attr: { href: blogEntryLink }, text: title"></a>
</h3>
<br /><br />
<span data-bind="html: body"></span>
<br />
<hr />
<br />
</div>
<!--- include knockout and dependencies (Jquery) --->
<script type="text/javascript" src="blog.js"></script>
blog.js
function vm() {
var self = this;
// Properties
self.blogs = ko.observableArray([]);
// consists of entryPostedDate, blogEntryLink, title, body
var blogApi = "/api/blog";
// Load data
$.getJSON(blogApi)
.success(function (data) {
self.blogs(data);
});
}
ko.applyBindings(new vm());
JQuery( $.getJSON(...)
)を使用してリクエストを実行したことに注意してください。バニラのJavaScriptはより多くのコードでも同じように動作します。
AJAXリクエスト中の「読み込みセクション/通知」
Blog.html
<div data-bind="visible: isLoading()">
Loading...
</div>
<div data-bind="visible: !isLoading(), foreach: blogs">
<br />
<span data-bind="text: entryPostedDate"></span>
<br />
<h3>
<a data-bind="attr: { href: blogEntryLink }, text: title"></a>
</h3>
<br /><br />
<span data-bind="html: body"></span>
<br />
<hr />
<br />
</div>
<!--- include knockout and dependencies (JQuery) --->
<script type="text/javascript" src="blog.js"></script>
blog.js
function vm() {
var self = this;
// Properties
self.blogs = ko.observableArray([]);
self.isLoading = ko.observable(true);
// consists of entryPostedDate, blogEntryLink, title, body
var blogApi = "/api/blog";
// Load data
$.getJSON(blogApi)
.success(function (data) {
self.blogs(data);
})
.complete(function () {
self.isLoading(false); // on complete, set loading to false, which will hide "Loading..." and show the content.
});
}
ko.applyBindings(new vm());
JQuery($ .getJSON(...)$)を使用してリクエストを実行したことに注意してください。バニラのJavaScriptはより多くのコードでも同じように動作します。
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow