【问题标题】:Django using Jquery to POST dataDjango 使用 Jquery 发布数据
【发布时间】:2012-08-02 22:25:42
【问题描述】:

我正在设计一个应用程序,其中您有连接,并且在页面一侧加载了待处理的连接请求列表。我遇到的问题是编写一个 jQuery 函数来接受请求并刷新页面上的 div 框。我不知道如何将连接请求的 id 传递给我的 jquery 函数,然后该函数将该 id 传递给我的视图以操作关联的对象。

这是我的 JS 代码:

function accept(id) {
  $.post("/accept/", function(json){
  alert("Was successful?: " + json['success']);
});

function addClickHandlers() {
  $("#accept").click( function() { accept(id) });
}
$(document).ready(accept);

这是我试图调用 JS 的 html:

      <table class="table table-condensed" style="margin-top:10px;">
    <tbody>
      {% for request in conReqs %}
      <tr>
        <td>
          <a href="#"><img src="{{ MEDIA_URL }}{{ request.creator.username }}<a onclick="accept({{ request.id }});">Accept</a> &middot; <i class="icon-thumbs-down"></i> <a href="#">Hide</a></p>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>

当我点击接受时,没有任何反应。

【问题讨论】:

    标签: jquery html ajax django for-loop


    【解决方案1】:

    您不需要onlick 属性,只需使用jQuery 不显眼地附加事件处理程序。你也不应该嵌套&lt;a&gt; 标签。

    function accept( id ) {
    
      $.post( "/accept/", function ( json ) {
    
        alert( "Was successful?: " + json[ 'success' ] );
    
      } );
    
    }
    
    
    function addClickHandlers() {
    
      $( ".accept" ).on( 'click', function ( event ) {
    
        event.preventDefault();
    
        accept( /\d+$/.exec( event.target.id )[0] );
    
      } );
    
    }
    
    
    $( document ).ready( function () {
    
      addClickHandlers();
    
      // If you really mean to call this at this point:
      accept();
    
    } );
    
    
    <table class="table table-condensed" style="margin-top:10px;">
      <tbody>
        {% for request in conReqs %}
        <tr>
          <td>
            <a href="#{{ request.id }}" class="accept"><img src="{{ MEDIA_URL }}{{ request.creator.username }}Accept</a> &middot; <i class="icon-thumbs-down"></i> <a href="#">Hide</a></p>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>    
    

    事件处理

    HTML:

    <a href="" id="some-link">Some link</a>
    

    JS:

    $( document ).ready( function () {
    
      // Select element(s). In this case, the one element with the ID
      // "some-link". Call `on()` on the selected elements to register an
      // event listener, in this case for the `click` event. The second
      // argument to `on()` is the handler function, which will be called
      // when the event occurs and will be passed a jQuery Event object.
    
      $( "#some-link" ).on( 'click', function ( event ) {
    
        // This prevents the default action associated with the event on
        // the target element. In the case of a click event on an
        // `a[href]` element, the default action would be to load the URL
        // that the `href` resolves to.
    
        event.preventDefault();
    
        // One of the properties of the Event object is `target` -- the
        // element that the event occured on. In this case the target will
        // be an `a[href]` element, so I can read `event.target.href`. If
        // the `a` element had nested elements, `event.target` could be
        // the nested element. In that case, you could do
        // `$( event.target ).closest( "a" )` to make sure you get the `a`
        // element that the event occured within.
    
        // Here I'm running a regular expression on `event.target.href` to
        // get a sequence of digits at the end.
    
        var id = /\d+$/.exec( event.target.href )[0];
    
      } );
    
    } );
    

    对于您问题中的用例,代码可以简化为如下内容:

    $( document ).ready( function () {
    
      $( ".accept" ).on( 'click', function ( event ) {
    
        event.preventDefault();
    
        var id = /\d+$/.exec( event.target.href )[0]; 
    
        $.post( "/accept/", { id : id }, function ( json ) {
    
          // ...
    
        } );
    
      } );
    
    } );
    

    【讨论】:

    • 感谢您的回答!尽管在 accept( /\d+$/.exec( event.target.id )[0] ); 上收到错误消息说 Uncaught TypeError: Cannot read property '0' of null :8000/:43 (anonymous function) :8000/:43 jQuery.event.dispatch jquery.js:3332 jQuery.event.add.elemData.handle.eventHandle跨度>
    • 我会在那条线之前做console.log( event.target.id ),看看你有什么。您是否按照我的建议设置了 HTML——&lt;a href="#{{ request.id }}" class="accept"&gt;
    • 对不起,我的错误很明显。我在代码中输入了错误的属性:id,而它应该是href。我更新了代码以纠正它。我对你的原始代码还没有那么远,但正如@dm03514 指出的那样,你显然需要将必要的数据发送到服务器,所以如果这最终成为最关键的事情,显然他的回答应该被我接受,但我仍然建议您结合我的建议——不要嵌套&lt;a&gt; 标签并不显眼地附加事件处理程序。
    • 你们俩都应该得到答案,但是如果没有您的代码结构和逻辑,即使修复了帖子,我也不会得到任何结果。我有点困惑事件是如何工作的,我希望能得到解释,以便我知道将来如何实现类似的东西。
    • 好的。 @dm03514 如果您给他们留下评论,提及他们的回答如何有帮助,您可能会喜欢它。我在我的答案中添加了一个关于事件处理一般如何工作的部分。不确定您是否对此有具体问题。此外,如果您在此处发表评论,显示您传递给 $.post() 的数据,我会将其放在我的答案中,以使其更加完整,以供将来查看此问题的任何人使用。
    【解决方案2】:

    您实际上并未发布任何数据。调试 javascript 时确保控制台已打开,这将显示所有语法错误和请求。学习如何调试代码很重要。随意使用console.log 来找出代码的哪些部分正在执行以及哪些部分没有执行。

    您可以在 url 之后发布数据,传递带有数据的对象

    var postData = {'id': id};
     $.post("/accept/", postData, function(json){
    

    在您的 django 视图中,您可以通过

    访问 id

    request.POST.get('id')

    【讨论】:

    • 感谢您的提示。这是我第一次使用 javascript,所以在涉及到这些东西时我是一个相当大的菜鸟。
    • 你在火狐上吗?如果是这样的话,萤火虫是绝对必要的!如果您使用的是 chrome,您可以右键单击并“检查元素”,这将打开控制台。 console.log 让您“打印”到控制台。所以console.log('here') 将显示在控制台选项卡中的“此处”。
    • 是的,我在 Chrome 上,我之前使用过检查元素进行 html 调试,但从来没有用于 JS。
    • 非常感谢您的回答!如果没有它,我将无法完成我的算法,但 JMM 提供了 JS 的核心逻辑,这是我真正需要的,所以我选择了他作为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2012-07-14
    • 2011-09-09
    相关资源
    最近更新 更多