Ajax不工作仍然刷新页面

时间:2018-03-12 08:31:40

标签: javascript jquery ajax

我想输入post,然后按enter后,它应该用新数据替换<div id="mainPagePosts"></div>而不刷新页面。但是,在提交post之后,它仍然刷新了页面,尽管我确实以纯HTML格式获取了数据。

我尝试preventDefault()stopPropagation(),但没有任何效果。

JQuery的

$("#homePagePostInputButton").keypress(function(e) {
  if(e.which == 13) {
    e.preventDefault();
    e.stopPropagation();
    $.ajax({
        url: "main/home",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({post:{"text": $("#homePagePostInput").val()}})
    }).done(function(result){
        updateMainPagePosts(result);
        removeTextFromInput("homePagePostInput");
    }).fail(function(err){
        console.log(err);
    });
  }
});

var updateMainPagePosts = function(posts){
  var div = document.getElementById("mainPagePosts");
  div.innerHTML = posts; 
};

var removeTextFromInput = function(input){
  var removeThis = document.getElementById(input);
  removeThis.value = ""; 
};

HTML

<div class="col-6 columns">
    <div class="card card-center">
        <div class="card-header card-post">
            <form action="/main/home" method="POST">
                <input type="text" class="form-control" id="homePagePostInput" name="post[text]" aria-label="Default" aria-describedby="inputGroup-sizing-default" placeholder="What's on your mind, <%= user.firstName %>?">
                <input type="submit" id="homePagePostInputButton" style="display:none">
            </form>
        </div>
    </div>

    <div id="mainPagePosts">
        //To be replaced with new data via AJAX
        <% include ../ajaxSnippets/mainHome %>
    </div>

</div>

2 个答案:

答案 0 :(得分:0)

首先,删除表单后期操作

其次,将type =“submit”改为type =“button”

或更改

$("#homePagePostInputButton").keypress

$(".card-header.card-post form").submit

答案 1 :(得分:0)

发生这种情况的原因是您发布了请求,这就是您的网页刷新的原因。按照上一个答案中的建议,或保留HTML,但为表单的onSubmit事件设置处理程序,并使用preventDefault()方法并从中返回false。这样,如果禁用了javascript,您将保留功能,您仍然会发布表单。

编辑:这是代码:

$("form").on('submit', function(e) {
    //you actually don't need e.preventDefault();
    return false;
}

注意:这会阻止您网页中的每个表单提交。因此,您可能需要设置表单的ID并通过id而不是表单标记选择它,如下所示:

$("#yourFormID").on(... etc.
相关问题