【问题标题】:Ajax request is executed twiceAjax 请求执行两次
【发布时间】:2014-09-19 15:06:23
【问题描述】:

以下代码 sn-p 使用 jQuery 编写并用于发送数据,单击即可执行两次。两个 HTTP 请求都给出 200 作为响应。

$(function() {
    $('input[type=submit]').click(function() {
        $(this).unbind("click");
        $.ajax({
            type: "POST",
            url: "/publish/",
            data: $("#submit-story").serialize(),
            beforeSend: function() {
                $('#send-draft').html('saving...');
            },
            success: function(data) {
                $('#send-draft').html('Draft');
                //window.location.href = "/home/"
            }

        });

    });
});

这是 HTML 的 Django 模板。这是 django 模板,所以我跳过了页眉和页脚部分,因为它不包含与我的问题相关的任何内容。

<link rel="stylesheet" type="text/css" href="{% static 'workout/wysiwyg-advanced/css/font-awesome.min.css' %}" />

<script>
$(function() {
    $('#story').editable({});
});
</script>

<div class="header" id="new-story-head"> 
    <div id="logo">W</div><div id="story-writer">  <img src="{% static 'workout/images/business_user.png' %}" align="absmiddle" /> {{ user.username }} 
        <span id="send-draft"> Draft </span> </div>
    <div class="right-top">
        <button id="red">Delete</button>
       <!-- <button id="grey">History</button>-->
        <button id="grey">Send Draft</button>  
        <input type="submit" id="green" value="Publish">       
     </div> 
</div>




<div class="content" id="new-story">
    <div class="center">
        <form class="story"  name="story"   id="submit-story">{% csrf_token %}
            <div class="image"><img id="addheader" src="{% static 'workout/images/add-image.png' %}" /></div>

            <input type="text" id="title" name="title" placeholder="Title" value='{{blog.title}}' /> <br />
            <input type="text" id="sub_title" name="subtitle" placeholder="Subtitle" value='{{blog.subtitle}}'/> <br />
    <input type="hidden" name="blog_id" value="{{ blog_id }}" />
            <textarea name="content" placeholder="Write your Story" rows="50" cols="60" id="story">{{blog.content|safe}}</textarea>

        </form>

    </div>
</div>

【问题讨论】:

  • 确保您只为提交创建 1 个事件侦听器。无论是提交还是点击等。你能显示你的html吗?
  • 表单下方没有提交按钮。它还会提交表单吗?具有默认行为。

标签: javascript jquery ajax apache http


【解决方案1】:

尝试对提交按钮使用 onclick 事件

<button id="green" value="Publish" onclick="javascript:return callonclick();"></button>
<script>
function callonclick(){
//Do your ajax call here
return false;
}

</script>

【讨论】:

  • 这不起作用。就像我的情况一样,它再次提出两个请求
  • @HarshitChaudhary 使用 '$.ajax({type: "POST",url: "/publish/",data: $("#submit-story").serialize(),success:函数(数据){}});'在 onclick 函数中并摆脱其余的废话
  • 但是在处理请求时,我需要一个指示器来向用户保证它正在保存...
猜你喜欢
  • 2013-03-08
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多