表单提交中的jquery无限循环

时间:2013-12-22 20:23:11

标签: php jquery ajax wordpress

我已经创建了一个自定义wordpress插件,应该执行以下操作:

  • 在页面加载时,提交表单
  • ajax捕获它并执行其他一些功能
  • 结果返回

唯一的问题是插件开始重定向到另一个页面并无限循环。我已将它与jquery提交代码隔离,但我无法弄清楚我做错了什么。我希望你们能帮助一个睡眠不足的程序员。

  $('#searchform').submit(function(e) {
     e.preventDefault();
     $.ajax({
        type: 'POST',
         url: '../wp-content/plugins/otwcsl/getStores.php',
         data: $('#searchform').serialize(),
         success: function(response) {
           searchLocations(response);
           $('#searchform').unbind().submit();
         }
     });
   });

它在我的localhost环境中运行良好,但在'live'网站上疯狂了。我无法弄清楚断开连接,但我很确定问题出在这里。提前谢谢!

更新:我已将所有内容剪下来,直到看起来像这样:

$('#searchform').submit(function(e) {
    return false;
}

它已停止循环,但会从http://www.mypage.com/index.php/locations/重定向到http://www.mypage.com/index.php/?s=。我无法弄明白,因为它显然不是影响它的ajax。

最终更新:我终于解决了这个问题。我删除了所有“提交”功能,并使用了一个按钮点击。我在选项3中使用了here找到的答案。我猜测之前有一些脚本严重混乱了表单。不幸的是,我不能选择禁用脚本来找到根本原因。谢谢大家帮我排除故障!

4 个答案:

答案 0 :(得分:0)

你在ajax调用中有这段代码:

$('#searchform').unbind().submit();

在其中,您再次提交表格。我猜这就是出了什么问题。

答案 1 :(得分:0)

无限循环,因为如果提交是seccussfull,则再次提交表单:

success: function(response) {
           searchLocations(response);
           $('#searchform').unbind().submit();
         }

为什么再次成功提交?删除它,它会工作!

它应该是:

success: function(response) {
               searchLocations(response);
             }

更新:

你的提交功能应该是这样的:

var _form = $('#searchform');
_form.unbind();
_form.submit(function(e) {
     e.preventDefault();
     $.ajax({
         type: "POST",
         url: "../wp-content/plugins/otwcsl/getStores.php",
         data: _form.serialize(),
         success: function(response) {
           //searchLocations(response); // check this method may be its submit the form again
         }
     });

});

答案 2 :(得分:0)

检查服务器的响应并在ajax调用中设置propper数据类型。

答案 3 :(得分:0)

您可以使用以下方法调试ajax:

$.ajax({
  url: $form.attr("action"),
  type: $form.attr("method"),
  data: $form.serializeArray()
}).fail(function(jqXHR, textStatus, errorThrown) {
  console.log(jqXHR, textStatus, errorThrown);
}).done(function(data, textStatus, jqXHR) {
  console.log(data, textStatus, jqXHR);
});