【问题标题】:Submit a form without refreshing a page using ajaxForm使用 ajaxForm 提交表单而不刷新页面
【发布时间】:2016-06-23 05:46:02
【问题描述】:

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

我有一个带有 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 开头的表单成功提交。成功后,表单将提交到更新购物车内容的购物车脚本,然后使用 ajax .load 调用 jsrefresh.php 将更新后的 html 回显到显示在屏幕顶部的迷你购物车中的 div .然后(这是需要正确执行的部分)jsrefreshincart.php 在循环中被调用(变量 count 保存页面上的表单总数)它更新页面上所有表单中所有 div 中的 html,并提供有关如何操作的信息购物车中有很多物品以及它们的价格。
是否有任何方法可以在没有循环的情况下执行此操作,因为只有提交的表单中的 div 需要更新?

【问题讨论】:

    标签: javascript php jquery html ajax


    【解决方案1】:

    这里的主要问题不是你有一个循环,而是你里面有一个服务器调用。处理这个问题的最好方法是改变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 of forms”之外的其他方式来跟踪数据 - 类也可以工作
    • 我的假设是任何以ectform 开头的ID 都是捕获此功能的表单;如果不是这种情况,上述解决方案的某些部分可能没有意义

    【讨论】:

      【解决方案2】:

      在查看了 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 次服务器调用。当产品页面上最多显示 25 个产品/表单时,我之前的脚本最多进行了 50 次调用。 我可以修改这个脚本和 php 脚本,只需一个调用即可完成所有操作,但网站上的其他页面没有产品,只有迷你购物车,因此更容易将脚本分开。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-13
        相关资源
        最近更新 更多