简体   繁体   English

从.ajax()调用加载knockout.js observableArray()

[英]loading a knockout.js observableArray() from .ajax() call

This puzzles me. 这让我很困惑。 It must be something small I'm not seeing. 它一定是我看不到的小东西。 I'm trying to load a very simple observableArray in knockout with an ajax call. 我正在尝试使用ajax调用在knockout中加载一个非常简单的observableArray

javascript JavaScript的

// we bind the array to the view model property with an empty array.
var data = [];   
var viewModel = {
    vendors: ko.observableArray(data)
};
ko.applyBindings(viewModel);

$(function () {
    // on this click event, we popular the observable array
    $('#load').click(function () {
        // WORKS. Html is updated appropriately.
        viewModel.vendors([{ "Id": "01" },{ "Id": "02" },{ "Id": "03" }]);

        // DOES NOT WORK. Fiddler2 shows the same exact json string come back 
        // as in the example above, and the success function is being called.
        $.ajax({
            url: '/vendors/10',
            dataType: 'json',
            success: function (data) {
                viewModel.vendors(data);
            }
        });
    });
});

html HTML

<button id="load">Load</button>
<ul data-bind="template: { foreach: vendors }">
    <li><span data-bind="text: Id"></span></li>
</ul>

Question: Why does the successful ajax call, who's data variable value matches byte-for-byte the hard typed value, not trigger the html refresh? 问题:为什么成功的ajax调用,谁的data变量值匹配逐字节的硬类型值,而不是触发html刷新?

There is no reason this would not work fine. 没有理由这不会很好。 As this demonstrates. 如此证明。

http://jsfiddle.net/madcapnmckay/EYueU/ http://jsfiddle.net/madcapnmckay/EYueU/

I would check that the ajax post is actually returning json data and that that json is an array and that it's being parsed correctly. 我会检查ajax帖子实际上是否返回json数据,并且json是一个数组并且它正在被正确解析。

I had to tweak the ajax call to get the fiddle ajax handlers to work correctly. 我不得不调整ajax调用以使小提琴ajax处理程序正常工作。

Nothing more I can think of. 我无法想到更多。

Hope this helps. 希望这可以帮助。

var self=this;
//var self first line in model

$.ajax({
            url: ",
            dataType: "json",
            contentType: 'application/json',
            type: "POST",
            data: JSON.stringify({ }),
            processdata: true,

            beforeSend: function () {
                $.mobile.loading('show');
            },

            error: function (xhr, textStatus, errorThrown) {
                alert('Sorry!');
            },

            success: function (data) {

                $.mobile.loading('hide');
                if (data.result!= '') {
                    self.vendors(data.result);



                } else {
                    self.vendors({something});

                }
            }
        });

Use self.vendors not this viewModel.vendors 使用self.vendors而不是this viewModel.vendors

Here is what I done in my MVC .net app with knockout and jquery. 这是我在我的MVC .net应用程序中使用knockout和jquery完成的。

 // Scripts/groItems.js (function () { var ViewModel = function () { items = ko.observableArray(), ItemName = ko.observable(), Img = ko.observable(), Qty = ko.observable() } $.getJSON('/Items2/AllItems', function (data) { for (var i = 0; i < data.length; i++) { self.items.push(data[i]); } }); var vm = new ViewModel(); $(function () { ko.applyBindings(vm); }); }()); 
 @model IEnumerable<GroModel.Item> @{ ViewBag.Title = "Index"; } <p> @Html.ActionLink("Create New", "Create") </p> <div data-bind="text: items().length"></div> <table class="container table table-hover"> <thead> <tr> <th>Item name</th> <th>img</th> <th>qty</th> </tr> </thead> <tbody data-bind="foreach: items"> <tr> <td data-bind="text: ItemName"></td> <td data-bind="text: Img"></td> <td data-bind="text: Qty"></td> </tr> </tbody> </table> @section Scripts { <script src="~/Scripts/knockout-3.4.2.js"></script> <script src="~/Scripts/groItems.js"></script> } 

Following is part of my code at the Items2Controller.cs 以下是我在Items2Controller.cs的代码的一部分

    private GroContext db = new GroContext();
    public JsonResult AllItems()
    {
        return Json(db.Items.ToList(), JsonRequestBehavior.AllowGet);
    }

在此输入图像描述

Hope this will help. 希望这会有所帮助。 Thanks 谢谢

We can use a simple JavaScript util function as a work-around. 我们可以使用简单的JavaScript util函数作为解决方法。

Instead of viewModel.vendors(data); 而不是viewModel.vendors(data); , wrapping with eval (research the dangers of eval first) will work. 用eval包装(首先研究eval的危险)会起作用。

eval("viewModel.vendors("+JSON.stringify(data)+");");

This is bug I think, Knockout's sample is working when we use it with wrapper class: 这是我认为的错误,当我们将它与包装类一起使用时,Knockout的示例正在运行:

public class ResultWrapper
{
    public Title {get;set;}
    public List<Result> {get;set;}
}

http://learn.knockoutjs.com/#/?tutorial=webmail http://learn.knockoutjs.com/#/?tutorial=webmail

But if we return Results directly there is no way to bind it. 但是,如果我们直接返回结果,则无法绑定它。 (without extra applyBindings!) (没有额外的applyBindings!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM