11

I have some pages that I need to render via the server side to make them search engine friendly. For search engines, it should function as a classic website. For users, I want to make the interface more interactive. My thought is to render the page server side, then use knockout and jquery to fetch the data again via ajax and bind it to the page.

I'm concerned about having flashes of no content, or duplicated content. Is there a best practice/pattern for cases like this?

The process would look like this:

  1. Render page using server side, including a long list of html elements.
  2. Use jQuery to fetch the same data already rendered to the page.
  3. Clear server side content with jquery.
  4. Bind ajax to knockout template, which effectively renders the page as it was previously.
  5. Subsequent clicks to page through data by a normal user uses ajax and knockout to render the data.
  6. Search engine can follow standard links to see the same data as the user.

The part I'm hung up on is how to pre-render, clear, and re-render with knockout/jquery.

Maybe my thought process is off a bit, I'd love to hear feedback.

4

5 回答 5

8

它是可行的,基本上是从服务器端填充您的数据,但是从淘汰部分将“数据绑定”属性添加到您的输入中,通过获取字段值来设置您的可观察值。

这是一个简单表格的示例:

MVC部分:

public ActionResult Index()
{
    Person newPerson = new Person()
    {
        FirstName = "John",
        LastName = "Smith"
    };

    return View(newPerson);
}

而你的观点:

<div id="main">
    <div>
        First Name:
        @Html.TextBoxFor(p => p.FirstName, new { data-bind = "value: firstName" })
    </div>
    <div>
        Last Name:
        @Html.TextBoxFor(p => p.LastName, new { data-bind = "value: lastName"})
    </div>

    <input type="button" data-bind="click: showValues" value="Show" />
</div>

最后是你的淘汰赛部分:

var personViewModel = function () {

    var self = this;

    self.firstName = ko.observable($("#FirstName").val());
    self.lastName = ko.observable($("#LastName").val());

    self.showValues = function () {
        alert(self.firstName() + " " + self.lastName());
    }
};

ko.applyBindings(new personViewModel());

希望这适用于您的情况。

编辑:修复 data_bind 到 data-bind 的错字

于 2013-06-28T12:01:32.017 回答
7

您可以尝试淘汰预渲染绑定处理程序。它基本上按照 Tamim 的建议做,但它处理 foreach 并适用于任何数据绑定。

https://www.npmjs.com/package/knockout-pre-rendered

您还可以考虑使用“通用”的 React - 您可以使用相同的代码在服务器和客户端上呈现页面。由于 React 使用差异引擎,因此当服务器呈现的内容被客户端呈现的内容替换时,不会出现闪烁。

http://facebook.github.io/react/

http://reactjs.net/

于 2015-06-17T11:30:39.703 回答
1

您可以使用 Node 和一个简单的 DOM 实现(如 domino)呈现淘汰赛:

于 2017-04-28T14:34:14.643 回答
0

除了 Knockout 之外,这还使用了Durandal,但我遇到了同样的问题,这是我想出的解决方案:

https://github.com/bestguy/durandal-delayed-composition

于 2014-01-04T07:07:42.550 回答
0

也可以使用peTemplate绑定。对于 tempate 和 foreach 绑定,它不会重新生成 HTML,而是使用服务器端生成的 HTML。您唯一需要做的就是用几个指定数据键的属性来注释服务器中的 HTML。

于 2013-08-29T12:13:03.893 回答