简体   繁体   English

在jQuery AJAX成功后刷新一个回显的PHP变量吗?

[英]Refreshing a echoed PHP variable after jQuery AJAX success?

I have a shopping cart in Codeigniter in which products are added to the cart using (jQuery) Ajax. 我在Codeigniter中有一个购物车,其中使用(jQuery)Ajax将产品添加到购物车中。 In the header of each page it displays the number of contents in the cart using 在每个页面的标题中,它使用来显示购物车中的内容数量

<?php echo $this->cart->total_items(); ?>

How can I update/refresh this variable when a product is added to the cart, as I am using AJAX to add products to the cart and thus the page isn't being reloaded when products are added. 将产品添加到购物车时,如何更新/刷新此变量,因为我正在使用AJAX将产品添加到购物车,因此添加产品时不会重新加载页面。 It seems pointless to use AJAX to do asyncronous stuff if I have to reload the page to get the new number of total items from the server. 如果我必须重新加载页面以从服务器获取新的总项目数,则使用AJAX进行异步操作似乎毫无意义。

Many thanks. 非常感谢。

You should be able to do this by making the element containing the Shopping Card Item Count easily addressable by JavaScript, so: 通过使包含“购物卡项目计数”的元素易于被JavaScript寻址,您应该能够做到这一点,因此:

<span id="total_items"><?php echo $this->cart->total_items(); ?></span>

Then, as part of the AJAX Function you perform, have the response contain the revised value for the total items, and then have your function replace the content of this span with that value. 然后,作为您执行的AJAX函数的一部分,让响应包含总项目的修订值,然后让您的函数用该值替换此范围的内容。

As I understood you, you need something to dynamically update your number of articles ? 据我了解,您需要一些东西来动态更新文章数量?

You can use jQuery PeriodicalUpdater to update that number "every once in a while" ( point it to a script that returns the current number only, ofc ). 您可以使用jQuery PeriodicalUpdater “偶尔”更新该数字(将其指向仅返回当前数字ofc的脚本)。

Don't think about PHP in this case — it's totally irrelevant. 在这种情况下,请不要考虑PHP –完全无关紧要。 What you need to do is modify content of that element client-side. 您需要做的是在客户端修改该元素的内容。 So if you have: 因此,如果您有:

<div id="total_items"><?php /* ... */ ?></div>

Then in your AJAX success handler you should do something like: 然后,在AJAX成功处理程序中,您应该执行以下操作:

$('#total_items').html('new item count');

First, you can update as many parts of the page as you want when you make a jQuery call. 首先,您可以在进行jQuery调用时根据需要更新页面的任意部分。 What is the format of the data that is being returned from the call? 呼叫返回的数据格式是什么? Lets say you are returning JSON, then the JSON string should include the total. 假设您要返回JSON,那么JSON字符串应包含总数。 Then in the callback of the AJAX call you can simply update the total count. 然后,在AJAX调用的回调中,您可以简单地更新总数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM