提交表单而不使用 ajaxForm 刷新页面

Submit a form without refreshing a page using ajaxForm

本文关键字:ajaxForm 刷新 表单 提交      更新时间:2023-09-26

我是一个完全的新手,所以请原谅我的无知。

我有一个带有php购物车的网站,当某些东西添加到购物车时,它会刷新到购物车页面。我想修改它,以便在添加产品时,购物车会在后台更新,并且产品页面不会刷新,而是使用唯一 id 更新各种div 中的 html。
我已经设法实现了这一目标,但我确信必须有一种更简单的方法,因为我的解决方案涉及一个循环,该循环遍历产品页面上的所有表单,而不仅仅是从提交的表单中更新div。

这是我的JavaScript,它位于产品页面的<head>标签内:

<script>
$(document).ready(function(){
       $("[id^=ectform]").ajaxForm({   // any form id beginning with ectform
          success:function(){
          $.ajaxSetup({ cache: false });
          $("#div1").load("jsrefresh.php");  // update html in div in minicart
             for (i = 0; i < count; i++) {     // count holds the number of forms on the page
                var d = "#glc" + i; //  div id to update
                var f ="#gld" + i;   // another div id to update
                var e = eval("z" + i);  // product id
       $(f).html('loading...').load("jsrefreshincart.php",{ prodynum: e, divno: d});
      };
     }
  });
});
</script>

该脚本使用 ajaxForm 来等待 ID 以 ectform 开头的任何表单的成功提交。成功后,表单将提交到更新购物车内容的 cart 脚本,然后使用 ajax .load 调用 jsrefresh.php它将更新的 html 回显到显示在屏幕顶部的迷你购物车中的div。然后(这是需要正确执行的位)jsrefreshincart.php 在一个循环中调用(变量计数保存页面上的表单总数),该循环更新页面上所有表单中所有div 中的 html,其中包含有关购物车中有多少项目以及它们的成本的信息。
有没有办法在没有循环的情况下做到这一点,因为只有提交的表单中的div 需要更新?

这里的主要问题不是你有一个循环,而是你有一个服务器调用。处理此问题的最佳方法是更改jsrefreshincart.php处理来自服务器的调用的方式。与其在循环内有多个调用,不如收集所有数据并在循环进行单个调用。

我不认为这是jQuery Form插件可以处理的事情;相反,你可能必须编写一些自定义代码(如下所示):

<script>
  $(document).ready(function() {
    $("[id^=ectform]").on('submit', function(e) {
      e.preventDefault();
      $('[id^=gld]').html('loading...'); // Trigger all loading messages simultaneously
      var formNums = [];
      for (i = 0; i < count; i++) {
        formNums.push(i);
      }
      $.post({
        $(this).attr('action'), // Where to send the form action
        formNums: formNums, // The data to send when submitting the Ajax call
        refreshCartData // The callback used to refresh the page
      });
    });
  });
  // Called automatically when the server responds with data
  function refreshCartData(data) {
    // Loop through all forms and update them
    for (var i = 0; i < data.length; i++) {
      // Update HTML
      $('#gld' + data[i].formNum).html(data[i].cartHTML);
    }
  }
</script>

您的jsrefreshincart.php应返回所有这些数据。例如:

<?php
// Used to load the cart data - I'm sure you have something similar
require_once('cart.php');
// Send everything back as JSON
header('Content-type: application/json');
// Initialize the data to send back
$data = array();
// Iterate over all data send to the server
foreach ($_POST['formNums'] as $formNum) {
  $data[] = array(
    // The unique ID for the form number
    'formNum' => $formNum,
    // Again, however you get the view data for your cart line items works fine
    'cartHTML' => Cart::getCartHTML($formNum)
  );
}
// Spit out the JSON data
echo json_encode($data);

一些其他建议:

  • 原始代码中的变量 d、e 和 f 不一定在 Ajax 往返期间全部更新
  • 您需要添加更多注释和缩进 - 这看起来很简单,但适当的文档是将您的问题传达给其他开发人员的最佳方式
  • 考虑使用除"表单count"之外的其他方法来跟踪数据 - 类也可以工作
  • 我的假设是,任何以 ID ectform开头的东西都是捕获此功能的形式;如果不是这种情况,上述解决方案的某些部分可能没有意义

在看了 Dykotomee 的建议(谢谢)之后,它给了我一个想法,我可以修改我的脚本以在没有循环的情况下工作:

<script>
 $(document).ready(function(){ // when DOM is ready
   $("[id^=ectform]").on('submit', function(e) {  // on submission of any form with id beginning "ectform"
    e.preventDefault();             // prevent the form itself submitting the data
      var subformid = $(this).attr('id'); // set variable with the id of the submitted form
       $(this).ajaxSubmit({     // submit the form via ajax which will add the product to the cart
        success:function(){    //on successful submission of the form
         $.ajaxSetup({ cache: false }); // turn off cache so the updates will refresh on all browsers
         $("#div1").load("jsrefresh.php");  //  load div in mini cart with new updated cart quantity
        var str = subformid.replace("ectform", "");  // trim subformid to leave just the end digits and call this variable str
       var d = "#glc" + str;   // not important for purposes of explanation
      var f ="#gld" + str;  // f is the id of the div in the submitted form to be updated 
    var e = eval("z" + str);  // e is the product number
$(f).html('Adding item to Cart...').load("jsrefreshincart.php",{ prodynum: e, divno: d}); // send data to jsrereshincart.php and load updated html into div f.
      }
    });
   });
 });
</script>

我使用ajaxSubmit而不是ajaxForm,它允许我使用$("[id^=ectform]").on('submit', function(e) {.......触发表单的提交然后,我能够捕获与var subformid = $(this).attr('id');一起提交的表单的ID现在我有了提交的表单的 id,我能够使用 ajax .load 将更新的购物车 HTML 以该特定形式放入div 中,而不是遍历所有表单并逐个更新它们。该脚本现在每次提交表单总共仅进行 2 次服务器调用。当产品页面上最多显示 55 个产品/表单时,我以前的脚本最多进行了 50 次调用。我可以修改此脚本和 php 脚本以通过一次调用完成所有操作,但网站上的其他页面没有产品,只有迷你购物车,因此更容易将脚本分开。