【问题标题】:Sending data from Knockout.JS using AJAX使用 AJAX 从 Knockout.JS 发送数据
【发布时间】:2014-05-22 06:13:25
【问题描述】:

这对我有用;当我点击 UI 元素时,请求正在执行。

    self.removeTweet = function(tweet) {
         $.ajax({
                type: 'POST',
                url: nodeApiUrl + 'twitter/remove_tweet/',
                contentType: 'application/json',
                data: JSON.stringify({'index': $('#removeFromQueue').val() }),
                dataType: 'json',
                error: $.osf.handleJSONError
            });
        self.tweets.remove(tweet);
    };

这里是 Knockout.JS 循环

<div id = "foo">
    <!-- ko foreach: tweets -->

        <input id = "queuedTweet" data-bind="value: tweet"/>
        <a  class="btn btn-primary" data-bind="click: $parent.queueSubmit" >
            Send
        </a>
        <a id = "removeFromQueue" data-bind = "click: $parent.removeTweet, value: $index" class="btn btn-danger">
            Delete
        </a>

       </br>

     <!-- /ko -->
   </div>

我想使用 AJAX 发送$index 的值,但是

data: JSON.stringify({'index': $('#removeFromQueue').val() })

没有返回值。如何使用 AJAX 发送这些数据?我认为将$index 绑定到value 将是解决方案。

【问题讨论】:

  • 显示循环的开始,显示你的 appModel 中的变量
  • {'index': $('#removeFromQueue').val() } 在您的控制台中解析为什么?
  • 您正在使用a 标签上的值?
  • @pherris 它解析为 0。
  • @GôTô 您可以将其发布为答案吗?那行得通!谢谢

标签: ajax knockout.js


【解决方案1】:

您可以使用self.tweets.indexOf(tweet) 检索它,而不是将索引添加为锚点上的值:

self.removeTweet = function(tweet) {
     $.ajax({
            type: 'POST',
            url: nodeApiUrl + 'twitter/remove_tweet/',
            contentType: 'application/json',
            data: JSON.stringify({'index': self.tweets.indexOf(tweet) }),
            dataType: 'json',
            error: $.osf.handleJSONError
        });
    self.tweets.remove(tweet);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多