【问题标题】:Knockout ajax foreach loop not working淘汰赛ajax foreach循环不起作用
【发布时间】:2013-08-22 22:07:05
【问题描述】:

我正在尝试将一组数据绑定到我的淘汰赛模板,但是当我尝试绑定它时,我得到了

 Uncaught ReferenceError: Unable to parse bindings.
 Bindings value: foreach: attributes
 Message: attributes is not defined

下面是我将用来取回数据的 ajax 调用。我已将 self.attributes 替换为要返回的预期数据,以使其在 jsfiddle 中可测试。

$.ajax({
    url: '/api/MyApi',
    type: 'GET',
    dataType: 'json',
    data: {
        DamageId: urlCat
    },
    success:
           function (data) {
               ko.applyBindings(new DetailViewModel(currentDamage, fakeHistData, data));

           },
    error: function () {
    }
});


function DetailViewModel(data, damHist,attrs) {
var self = this;
self.details = data;
self.attributes  = '{[{"Id": 258,"Value": "Yes","AttributeId": 195,"AttributeName": "FurtherDamage","AttributeText": "Is the condition causing further damage to the property?"},{"Id": 259,"Value": "Zombie Attack","AttributeId": 196,"AttributeName": "Description","AttributeText": "Enter a description for the damage"}]}'
self.damHistory = ko.observableArray(damHist);
}

这是我的 HTML

<div class="itemAttributesContainer topBorder">
    <h4>Attributes</h4>
    <table id="attributeTable" data-bind="foreach: attributes">
        <tr>
            <td>
                <span class="attrQuestion" data-bind="text: AttributeText + ': '" />
                <span data-bind="text: Value" />
            </td>
        </tr>
    </table>
</div>

http://jsfiddle.net/2Tp4E/

【问题讨论】:

  • 在你的小提琴和你的问题中都没有foreach: attributes!请将您的问题更新为导致问题的实际代码!
  • 对不起,现已修复
  • 你的小提琴不合适。我没有看到任何jquery frameqork.jsknockout.js。修复它,提供适当的外部资源。
  • 你的小提琴永远不会工作,因为没有网址/api/MyApi

标签: javascript ajax jquery knockout.js


【解决方案1】:

您的小提琴无论如何都无法正常工作,请通过添加此代码进行检查。为此,您需要敲除映射插件。

Html:

    <table id="attributeTable" data-bind="foreach: attributes">
            <tr>
                <td>
                    <span data-bind="text: AttributeText() + ': '" />
                    <span data-bind="text: Value()" />
                </td>
            </tr>
        </table>

查看模型:

    self.attributes = ko.mapping.fromJSON('[{"Id": 258,"Value": "Yes","AttributeId": 195,"AttributeName": "FurtherDamage","AttributeText": "Is the condition causing further damage to the property?"},{"Id": 259,"Value": "Zombie Attack","AttributeId": 196,"AttributeName": "Description","AttributeText": "Enter a description for the damage"}]')

【讨论】:

  • 我已经根据剩下的 cmets 更新了 jsfiddle。我不需要通过将我的数组设置为我的响应字符串来覆盖 jquery 的引用,调用只是为了提供一些上下文
  • 您不理解@Tim B James 的上述内容,“/api/MyApi”在 jsfiddle 上不可用,它不是您的 api 项目!您可以将 data.json 文件放在资源中并在 ajax 请求中调用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 2015-05-06
  • 1970-01-01
  • 2014-05-10
  • 2013-11-25
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多