Ajax请求后页面刷新 [英] Page refreshes after ajax request

查看:243
本文介绍了Ajax请求后页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有一个仅包含text field的简单表格.当我们点击Submit时,在文本字段中写入的数据将存储在DB中(通过ajax存储). Ajax可以正常工作并提交数据,但是,页面会自动刷新,并且URL包含输入字段的内容.

Alright, I have a simple form comprising of only a text field. Data written in the text field is stored in DB when we hit submit (Stored via ajax). The ajax works fine and data is submitted, however, the page get's refreshed automatically and the URL contains the content of the input field.

我的表格:-

<form class="form-horizontal">
                <fieldset>

                <!-- Text input-->
                <div class="form-group">
                  <label class="col-md-4 control-label" for="message"></label>  
                  <div class="col-md-5">
                  <input id="message" name="message" type="text" placeholder="message" class="form-control input-md" required="">

                  </div>
                </div>

                <!-- Button -->
                <div class="form-group">
                  <label class="col-md-4 control-label" for="submit_message"></label>
                  <div class="col-md-4">
                    <button id="submit_message" name="submit_message" class="btn btn-success">Enter</button>
                  </div>
                </div>

                </fieldset>
                </form>

Ajax:-

$("#submit_message").click(function() {
    var message = $("#message").val();
    $.ajax({
      type: "POST",
      url: "ajax_getter.php?requestid=2",
      data: { message: message, c: c },
      dataType: "html"
    }).done(function( msg ) {
      //load_content();
      alert(msg);
});
});

PHP:-

//...
if($chat->insert("chat_threads", $arr))
    {
        echo 1;
    }
    else
    {
        echo 0;
    }

结果显示在popup中后,页面刷新,URL变为:- chat.php?message = 454545& submit_message = 为什么要刷新页面?

After the result is show in the popup, the page refresh and the URL becomes something like :- chat.php?message=454545&submit_message= Why is the page being refreshed ?

推荐答案

似乎正在提交您的表单.尝试阻止默认事件(即提交):

Seems that your form is being submitted. Try preventing the default event (i.e. submission):

$("#submit_message").click(function(e) {
    e.preventDefault();    // This prevents form from being sumbitted
    // the rest of your code
});

这篇关于Ajax请求后页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆