表格链接不能正常运作?

时间:2013-09-27 20:29:36

标签: jquery html forms

我正在开发一个有一些不可编辑的HTML的电子商务网站。他们提供的功能之一是“快速”添加到购物车按钮,当您点击它时,您将保留在您的页面上,但会弹出一个小小的窗口,显示购物车的内容,包括您刚刚添加的项目。我写了一个小脚本,当在产品的类别列表中显示时,将这个快速添加链接添加到所有产品,但是当您单击此链接时,它会将您发送到实际的购物车页面而不会打开迷你窗口。

我认为这种情况正在发生,因为它在一个表格内。我可能是错的,但这是我唯一可以想到它为什么会发生的事情。相关的HTML:

<form class="search_results_section" method="post" name="MainForm" id="MainForm" action="/searchresults.asp" onsubmit="return OnSubmitSearchForm(event, this);">
   <!-- other stuff -->
      <a class="addit" href="/ShoppingCart.asp?ProductCode=BBB-DWCB">Add To Cart</a>
   <!-- other stuff -->
</form>

<a class="addit" href="/ShoppingCart.asp?ProductCode=BBB-DWCB">Add To Cart</a>

两个链接完全相同,但是当我点击表单底部的链接时,它会按照我想要的方式执行操作,这会让您保持在页面上,但会打开迷你购物车窗口。表格中的一个,就产品本身而言,正在把我带到另一个页面。有没有人知道为什么会发生这种情况,或者我能做些什么来解决它?

我尝试过的一件事(但不起作用):

$(document).ready(function(){
   var $form = $('form[action="/searchresults.asp"]');
   $form.submit(function(){
      $.post($(this).attr('action'), $(this).serialize(), function(response){
            //
      },'json');
      return false;
   });
});

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:2)

你的表格是这样的

<form class="search_results_section" method="post" name="MainForm" id="MainForm" action="/searchresults.asp" onsubmit="return OnSubmitSearchForm(event, this);">

删除onsubmit="return OnSubmitSearchForm(event, this);并使用以下代码

$(document).ready(function(){
    $('#MainForm').submit(function(e){
        e.preventDefault();
        $.post($(this).attr('action'), $(this).serialize(), function(response){
            console.log(response)
      },'json'); // you suppose to return json from the server
    });
});

由于您在表单(MainForm)中有一个id,因此最好以这种方式和代码e.preventDefault();使用它,这会阻止表单提交的默认行为(停止提交)。< / p>

<强>更新

此外,在表单中,您有一个a标记,如

<a class="addit" href="/ShoppingCart.asp?ProductCode=BBB-DWCB">Add To Cart</a>

使用button/submit代替,这是您的代码中导航到另一个页面而不是表单提交的主要问题。使表单看起来像

<form class="search_results_section" method="post" name="MainForm" id="MainForm" action="/searchresults.asp">
    <!-- other stuff -->

    <input type="submit" class="addit" name="btn_sub"  />
</form>

<强>更新

如果您无法编辑表单并需要使用<a>标记而不是submit按钮,那么您必须将处理程序绑定到该链接的click事件,例如

$('#MainForm a.addit').click(function(e){
    e.preventDefault();
    $.get($(this).attr('href')+'&'+$(this).closest('form').serialize(), function(response){
        console.log(response)
    },'json');
});

并且,在服务器端,从$_GET数组中获取值,因为您在params标记(<a>)中使用了href="/ShoppingCart.asp?ProductCode=BBB-DWCB"和您的网址,因此只需将序列化的表单数据添加到当前url的末尾,并避免post(如果没有必要)。所以,你的url最终会看起来像

/ShoppingCart.asp?ProductCode=BBB-DWCB&forminput1=value1&forminput2=value2

因为这段代码

$(this).attr('href')+'&'+$(this).closest('form').serialize()

答案 1 :(得分:1)

如果您要将表单提交回自身,则无需指定操作:

<form name="MyForm" method="post" action="" ...>