weixin_33671935 2015-06-09 22:51 采纳率: 0%
浏览 244

Ajax请求页面重定向

I am loading a form named staff_view.php in main.php through ajax. It's loading fine but when I submit form to staff_post.php it's redirecting to it instead of showing in console, before I add the code for loading form using ajax it was posting fine but after it's redirecting.

Here is my code

$(document).ready(function() {            
    $('.content_load').load('staff_view.php');
    $('ul#nav li a').click(function() {
        var page = $(this).attr('href');
        $('.content_load').load(page);
        $('form.ajax').on('submit', function() {
            var that = $(this);
            url = that.attr('action'),     
                type = that.attr('method'), 
                data = {};

            that.find('[name]').each(function(index, value) {            
                var that = $(this),
                    name = that.attr('name'),
                    value = that.val();
                    data[name] = value;
            });

            $.ajax({
               url: url,
               type: type,
               data: data,
               success: function(response){
                   console.log(response);
               }
            });
        });
        clearAll();
        return false;
    });
});

function clearAll(){
    $("form :input").each(function(){
        $(this).val(""); 
    });
}
  • 写回答

3条回答 默认 最新

  • larry*wei 2015-06-09 23:02
    关注

    Because it's a form, and because you wish to submit via AJAX instead of the usual "redirect-to-page" method that forms automatically use, you must suppress the default action.

    Change this:

    $('form.ajax').on('submit', function(){
        var that = $(this);
        etc.
    

    to this:

    $('form.ajax').on('submit', function(e){  // <=== note the (e)
        e.preventDefault();                   // <=== e used again here
        var that = $(this);
        etc.
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?