本文介绍了提交表单而不使用ajaxForm刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我有一个php购物车的网站,刷新到购物车页面时,添加到购物车。我想修改它,以便在添加产品时,购物车在后台更新,产品页面不会刷新,但会使用唯一的ID更新各个div中的html。

我设法实现了这一点但我相信必须有一个更简单的方法,因为我的解决方案包含一个循环,可以浏览产品页面上的所有表单,而不仅仅是从提交的表单更新div。



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

 <脚本> 
$(document).ready(function(){
$([id ^ = ectform])。ajaxForm({//任何以ectform开头的表单id
success:function( ){
$ .ajaxSetup({cache:false});
$(#div1)。load(jsrefresh.php); //在minicart中更新html中的div
for(i = 0; i< count; i ++){// count保存页面上表单的数量
var d =#glc+ i; // div id to update
var f =#gld+ i; //另一个div id更新
var e = eval(z+ i); //产品ID
$(f).html('loading。 ...')。load(jsrefreshincart.php,{prodynum:e,divno:d});
};
}
});
});
< / script>

该脚本利用ajaxForm等待成功提交任何带有以ectform开头的Id的表单。成功时,表单被提交到更新购物车内容的购物车脚本,然后使用ajax .load调用jsrefresh.php,它将更新后的html回显到显示在屏幕顶部的迷你购物车中的div 。然后(这是需要正确执行的位)在循环中调用jsrefreshincart.php(变量计数保存页面上的表单总数),它会更新页面上所有表单中所有div的html,并提供有关很多商品都在购物车中,并且花费了多少。

有没有什么方法可以在没有循环的情况下做到这一点,因为只有提交表单中的div需要更新?

解决方案

这里的主要问题不是你有一个循环,而是你有一个服务器调用。处理这个问题的最好方法是改变 jsrefreshincart.php 处理来自服务器的调用的方式。而不是在循环中多次调用,收集所有数据并在循环之外进行一次 调用。



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

 < script> ('submit',function(e){
e.preventDefault(){
$(document).ready(function(){
$([id ^ = ectform] );
$('[id ^ = gld]')。html('loading ...'); //同时触发所有加载消息
var formNums = [];
for (i = 0; i formNums.push(i);
}
$ .post({
$(this).attr(' action'),//发送表单动作的位置
formNums:formNums,//提交Ajax调用时发送的数据
refreshCartData //用于刷新页面的回调
} );
});
});

//当服务器响应数据时自动调用
函数refreshCartData(data){
//遍历所有表单并更新它们
for(var i = 0; i< data.length; i ++){
//更新HTML
$('#gld'+ data [i] .formNum).html(data [i] .cartHTML);
}
}
< / script>

您的 jsrefreshincart.php 所有这些。例如:

 <?php 

//用于加载购物车数据 - 确保你有类似的
require_once('cart.php');
//将所有内容以JSON形式返回
头('Content-type:application / json');
//初始化数据发回
$ data = array();
//迭代所有发送到服务器的数据
foreach($ _POST ['formNums'] as $ formNum){
$ data [] = array(
// The表单编号的唯一ID
'formNum'=> $ formNum,
//然而,您再次获得购物车订单项的视图数据仍然正常工作
'cartHTML'=> Cart :: getCartHTML($ formNum)
);
}
//吐出JSON数据
echo json_encode($ data);

一些额外的建议:


  • 您的原始代码中的变量d,e和f在Ajax往返期间不一定全部更新

  • 您需要添加更多注释和缩进 - 看起来好像简单但正确的文档是将问题传达给其他开发人员的最佳方式
  • 考虑使用另一种方式来跟踪除 count of forms - 类也可以工作

  • 我的假设是任何以ID ectform 开头的东西都是一个表单捕获此功能;如果情况并非如此,上述解决方案的一部分可能没有意义。


I'm a total novice so please excuse my ignorance.

I have website with a php shopping cart that refreshes to the cart page when something is added to to the cart. I want to modify it so that when a product is added, the cart updates in the background and the product page does not refresh but updates the html in various divs with unique id's.
I have managed to achieve this but I am sure that there must be a simpler way as my solution involves a loop that trawls through all the forms on the product page rather than just updating the divs from the form that was submitted.

Here's my JavaScript which is inside the <head> tags of the product page:

<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>

The script utilises ajaxForm to wait for the successful submission of any form with an Id beginning with ectform. On success, The form is submitted to the cart script which updates the cart contents and then ajax .load is used to call jsrefresh.php which echoes back the updated html to a div in a mini cart which is displayed at the top of the screen. Then (this is the bit that needs doing properly) jsrefreshincart.php is called in a loop ( the variable count holds the total number of forms on the page ) which updates html in all divs within all the forms on the page with information about how many items are in the cart and how much they cost.
Is there any way of doing this without the loop as only the divs within the form that was submitted need to be updated ?

解决方案

The major problem here is not that you have a loop, but that you have a server-call inside of it. The best way to handle this is to change the way that jsrefreshincart.php handles calls from the server. Instead of having multiple calls inside the loop, collect all the data and have a single call outside the loop.

I don't think that's something the jQuery Form plugin can handle; rather, you'll probably have to write some custom code (like below):

<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>

Your jsrefreshincart.php should return data for all of this. For example:

<?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);

Some additional suggestions:

  • Your variables d, e, and f in your original code are not necessarily all updated during the Ajax round-trip
  • You need to add more commenting and indentation - it seems simple, but proper documentation is the best way to communicate your problems to other developers
  • Consider using a different way to keep track of data besides a "count of forms" - classes can work too
  • My assumption is that anything starting with an ID of ectform is a form to have this functionality captured in; if this is not the case, parts of the above solution might not make sense

这篇关于提交表单而不使用ajaxForm刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 13:51