Php 更改表单以使用jQuery并避免页面刷新

Php 更改表单以使用jQuery并避免页面刷新,php,jquery,css,forms,Php,Jquery,Css,Forms,为了使用jQuery,我正在尝试更改下面的表单标记。现在,单击按钮会将显示从行更改为列,反之亦然,但我希望避免页面刷新。我对jQuery真的是个新手,当我自己尝试改变它时,我不能诚实地说出我的错误是什么 <form id="rowsToColumns" action="index.php?main_page=specials&disp_order=1" method="POST"> <input type="hidden" name="style_changer

为了使用jQuery,我正在尝试更改下面的表单标记。现在,单击按钮会将显示从行更改为列,反之亦然,但我希望避免页面刷新。我对jQuery真的是个新手,当我自己尝试改变它时,我不能诚实地说出我的错误是什么

<form id="rowsToColumns" action="index.php?main_page=specials&disp_order=1" method="POST">
    <input type="hidden" name="style_changer" value="columns"/>
    <button type="submit" class="btn btn-large btn-primary" type="button">Change to Column</button>
</form>

<form id="columnsToRows" action="index.php?main_page=specials&disp_order=1" method="POST">
    <input type="hidden" name="style_changer" value="rows"/>
    <button type="submit" class="btn btn-large btn-primary" type="button">Change to Rows</button>
</form>

更改为列
换行
我还尝试让按钮在单击时调用不同的样式表。如上所述,显示从/更改为行/列不需要此样式表。实际页面使用php编写,如下所示:

<?php $this_page =  zen_href_link($_GET['main_page'], zen_get_all_get_params()); ?>
<div id="style_changer">
    <?php if($current_listing_style == 'rows') {?>
    <form id="rowsToColumns" action="<?php echo $this_page;?>" method="POST">
        <input type="hidden" name="style_changer" value="columns"/>
        <button type="submit" class="btn btn-large btn-primary" type="button">Change to Column</button>
    </form>
    <?php } else { ?>
    <form id="columnsToRows" action="<?php echo $this_page;?>" method="POST">
        <input type="hidden" name="style_changer" value="rows"/>
        <button type="submit" class="btn btn-large btn-primary" type="button">Change to Rows</button>
    </form>
    <?php } ?>
</div>

如果问题是“如何更改表单以使用jQuery并避免页面刷新”,那么它就是您的朋友,因为它可以将任何html表单转换为支持ajax的表单


只需按照他们的指示操作,您将很快使其工作(前提是您的表单已按原样工作)。

您可以通过阻止“提交”按钮上的默认操作来阻止默认表单提交

 $('button[type=submit]').submit( function(e){

       e.preventDefault(); // Stops the form from submitting 
  });

对于非常模糊的方法,您可以使用
$.ajax
,并利用读取
预先存在的属性来决定提交方法,并将元素的值作为提交数据读取:

$('form').on('submit',function(e){
  var $form = $(this);
  // submit the form, but use the AJAX equiv. instead of a full page refresh
  $.ajax({
    'url'     : $form.attr('action'),
    'method'  : $form.attr('type'),
    'data'    : $form.serialize(),
    'success' : function(response){
      // process response (make CSS changes or whatever it is
      // a form submission would normally do)
    }
  });
  // prevent the normal submit and reload behavior as AJAX is now
  // handling the submission
  e.preventDefault();
});

但是,为了实现这一点,您需要对仅用于AJAX请求的精简PHP响应进行一些修改(避免重新发送头、脚本标记等,只返回jQuery可用于做出UI决策的原始数据)。

最好将提交事件附加到表单中。我认为IE中的按钮类型存在一些问题(但不是100%确定)