【问题标题】:how to get the 'id' of form id in jquery如何在jquery中获取表单id的'id'
【发布时间】:2013-07-22 22:10:37
【问题描述】:

我无法将form id 传递给views.py 页面。 jQuery 不会将“id”传递给视图页面。请告诉我我做错了什么。

这是我的 jQuery。

$(function(){
        $('.chatroom').submit(function () {

            $.ajax({
                type: "POST",

                url: "/dashboard",
                data : {
                            'chatroom_id' : $(this).attr('id')
                        },

                    });

            });

这是我的模板

{% for key, values in chat_data.items %}
        <div class="container-fluid" alt = {{key}}>
            <div class="row-fluid">
               <div class="span2">
                 {{values.from}} <br/> {{values.init_query}}
                </div>

            <div class="span10 well">

                {% for k in values.chat %}

                        <label> Text : {{k.text}} </label> 
                        <label> {{k.date_time}} </label>

                {% endfor %}        

            <form action = "#" method = "POST" id = {{key}} class="chatroom">
               {% csrf_token %}
                   {{ form.as_p }}

                <input type="submit" value = "Sent" class="btn btn-primary"> 
            </form>

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

Views.py

if request.is_ajax():
    if request.method == "POST":
        chatroom_id = request.POST['chatroom_id']
else:
    chatroom_id =''

print chatroom_id

当我删除 if request.is_ajax() 条件时,它会显示错误消息 "Key 'chatroom_id' not found in <QueryDict: {u'reply': [u''], u'csrfmiddlewaretoken': [u'yIJct9O7WfyPnWmDosW9N5TEklRwoIHP']}>"

【问题讨论】:

  • 你应该删除data右括号之后的最后一个,
  • 你检查页面源了吗?你得到{{key}} 值了吗?
  • @KhawerZeshan- 是的,页面源中存在键值。请有任何建议
  • 是的@KhawerZeshan- 键值确实存在。并且表单 id 有它。
  • 你需要阻止默认提交动作e.preventDefault()

标签: jquery django django-views


【解决方案1】:

您说您必须删除is_ajax() 方法,这表明您实际上根本看不到Ajax 帖子,而是标准浏览器表单提交。这是因为您没有阻止 jQuery 代码中的默认提交操作。

应该是:

$('.chatroom').submit(function(event) {
    event.preventDefault();
    $.ajax({
        ...

【讨论】:

    【解决方案2】:

    以下不是您的问题的原因,但会导致 JS 错误(语法错误):

    $(function(){
        $('.chatroom').submit(function () {
            $.ajax({
                type: "POST",
                url: "/dashboard",
                data : {
                    chatroom_id: $(this).attr('id')
                } // you had a dangling comma here
            });
        }); // you were missing a closing bracket and paren here
    });
    

    【讨论】:

    • 我之前注意到了拼写错误,但我仍然无法从中得到结果。请有任何建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多