未捕获的TypeError:无法读取属性' split'未定义的(匿名函数)

时间:2016-04-17 07:13:19

标签: javascript jquery python django

我不确定为什么我会收到此错误,我只是想将在索引页面中工作的表单移动到帖子页面。我只是简单地移动了表格但没有工作;未捕获的TypeError:无法读取属性' split'由于某种原因未定义(匿名函数)

            <div>

        {% crispy comment_form comment_form.helper %}

                </div>

<script>
$(document).ready(function() {


     $(document).on('submit', 'form', function(e){
      e.preventDefault();
      if($(this).parents("tr").length != 0) {
        parent_id = $(this).parents("tr").attr("id").split("_")[1];
        data_str = $(this).serialize() + "&parent_id=" + parent_id;
      } else {
        data_str = $(this).serialize();
      }
      $.ajax({
        type:'POST',
        url:'/comment/create/',  // make sure , you are calling currect url
        data:data_str,
        success:function(json){              
          alert(json.message); 
          if(json.status==200){
             var comment = json.comment.trim();
             var user = json.user;
             /// set `comment` and `user` using jquery to some element
              if(!json.parent) {
                $(comment).insertBefore('.table tr:first');
              }
              else {
                $(comment).insertBefore('#comment_' + json.parent_id + ' #child_comment:first');
                $(".replies").text("reply" + json.comment_count + "see");
              }
           }  

        },
        error:function(response){
          alert("some error occured. see console for detail");
        }
      });
    });

我的表格

class CommentForm(forms.Form):
    comment = forms.CharField(
        widget=forms.Textarea(attrs={"placeholder": "leave"})
    )
    #hidden_field = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, hidden_data=None, data=None, files=None, **kwargs):
        super(CommentForm, self).__init__(data, files, kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False
        self.helper.add_input(Submit('submit', css_class='btn btn-default'))
        if hidden_data:
            self.helper.add_input(Hidden('post_id', hidden_data['post_id']))
            self.helper.add_input(Hidden('origin_path', hidden_data['origin_path']))
            if hidden_data.get('parent_id', None):
                self.helper.add_input(Hidden('parent_id', hidden_data['parent_id']))
\

我的观点

  def comment_thread(request, id):
        comment = Comment.objects.get(id=id)
        comments = comment.post.commented_post.all()
        for c in comments:
                c.get_children()
        hidden_data = {
                    "post_id" : comment.post.id,
                    "origin_path" : request.get_full_path,
                    "parent_id" : None
                }
        comment_form = CommentForm(hidden_data=hidden_data) 
        context = {
        "comment": comment,
        'comment_form':comment_form
        }
        return render(request, "comments/comment_thread.html", context)

编辑:

{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block content %}

<a href="{{ comment.get_origin }}">Go Back</a>

<table class='table'>

<tr><td>{{ comment.get_comment }} 
<br/><small>via {{ comment.user }} | {{ comment.timestamp|timesince }} ago </small>
                {% if not comment.is_child %}
                <ul>
                {% for child in comment.get_children %}
                <li>{{ child.get_comment }} 
                <small>via {{ child.user }}</small>


                </li>
                {% endfor %}
                </ul>
                <div>

        {% crispy comment_form comment_form.helper %}

                </div>
                {% endif %}


</td></tr>


</table>

<script>
$(document).ready(function() {


     $(document).on('submit', 'form', function(e){
      e.preventDefault();
      if($(this).parents("tr").length != 0) {
        parent_id = $(this).parents("tr").attr("id").split("_")[1];
        data_str = $(this).serialize() + "&parent_id=" + parent_id;
      } else {
        data_str = $(this).serialize();

      $.ajax({
        type:'POST',
        url:'/comment/create/',  // make sure , you are calling currect url
        data:data_str,
        success:function(json){              
          alert(json.message); 
          if(json.status==200){
             var comment = json.comment.trim();
             var user = json.user;
             /// set `comment` and `user` using jquery to some element
              if(!json.parent) {
                $(comment).insertBefore('.table tr:first');
              }
              else {
                $(comment).insertBefore('#comment_' + json.parent_id + ' #child_comment:first');
                $(".replies").text("reply" + json.comment_count + "view all");
              }
           }  

        },
        error:function(response){
          alert("some error occured. see console for detail");
        }
      });
    });

1 个答案:

答案 0 :(得分:0)

当您尝试设置$(this).parents("tr").attr("id") var时,

parent_id返回undefined。我看到你在视图中传入的是“parent_id”:无。什么是HTML的样子?我认为一个元素应该具有jQuery的ID,并且你没有在视图中设置它。如果是这样,您可以查看if ($(this).parents('tr').attr('id')) { /* split in here */ }