在PHP中使用Ajax在foreach循环中更新数据 [英] Updating data in foreach loop using ajax in PHP

查看:267
本文介绍了在PHP中使用Ajax在foreach循环中更新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在codeigniter中工作,并在div中使用foreach循环显示数据库
,这是我的代码

I am working in codeigniter, and using foreach loop in a div to display content of the database here is my code

<?php foreach($values as $row): ?>
<div class="col-xs-6 col-md-3" id="<?php echo $row->album_id ?>">
<?php echo $row->album_name; ?>
</div>
<?php endforeach; ?>

我的问题是如何使用ajax更新 $ values的值,以及如何刷新此div的内容。

my question is how can I update the value of "$values" using ajax, and how can I refresh the content of this div.

推荐答案

步骤1:
在PHP端,添加一个用于请求值的操作:

Step1: On PHP side add an action for requesting the values:

<?php
$myValues = array(); // maybe from database?
header('Content-type: application/json');
echo json_encode($myValues);
?>

这是您的控制器操作,用于将JSON数据发送到客户端。

This is your controller action for sending JSON data to the client side.

步骤2:
在客户端:(a)添加jQuery,然后(b)执行ajax调用以从上述操作中获取数据,如下所示:

Step2: On client-side: (a) add jQuery and then (b) do a ajax call to fetch the data from your action above, like so:

$.getJSON( "index.php?getValueAction", function( data ) {
   alert(data);

   // to access the individual properties you would do
   alert(data.property); 

   // use jquery selectors to target the element, where you want the content
   $("#myDiv").append(...);
   // you should create a proper html element before inserting it :)
}

getJson()调用的第一个参数取决于您的Codeigniter路由配置。
有些有 / index / forum / show ,有些有 index.php?controller = forum& action = show
插入您使用的URL样式,以向CI发送请求。

The first argument of the getJson() call depends on your Codeigniter routing configuration. Some have /index/forum/show, others have index.php?controller=forum&action=show. Insert the URL style you use, to make the request to CI.

此答案在客户端JS上进行迭代并准备一个dom元素

The this answer does the iteration on client-side JS and prepares a dom-element for insertion, right.

-
另一种方法是保留PHP部分,就像您拥有它一样,并在AJAX请求上发送整个HTML部分。那不是很好,但是可以。然后,这是对提供HTML片段的控制器/操作的基本Ajax Get请求。

-- An alternative would be to keep the PHP part like you have it and send the whole HTML part over on an AJAX request. That's not very nice, but works. Then it's a basic Ajax Get request to the controller/action providing the HTML fragment.

$.get( "URL", function( data ) {
   $("#myDiv").html( data );
});

这篇关于在PHP中使用Ajax在foreach循环中更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆