在 PHP 和 Javascript 之间传输数组的最佳方式 [英] Best way to transfer an array between PHP and Javascript

查看:20
本文介绍了在 PHP 和 Javascript 之间传输数组的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个从数据库中检索到的记录数组.数组为格式;

So I have an array of records retreived from a database. The array is in the format;

$rows[0]['id']=1;
$rows[0]['title']='Abc';
$rows[0]['time_left']=200;


$rows[1]['id']=2;
$rows[1]['title']='XYZ';
$rows[1]['time_left']=300;
//And so on upto 10-20 rows

将此数组传输到我的 javascript 代码的最佳方法是什么?我希望 javascript 能够遍历所有记录,并使用id"属性,用一些信息更新带有该 id 的 div.

What's the best way of transferring this array over to my javascript code? I'd like the javascript to be able to loop through all of the records, and using the 'id' attribute, update the div with that id with some information.

我的 javascript 代码位于外部 .js 文件中,但我能够在我页面的 HTML 代码中执行 php 代码.所以我可以做这样的事情:

My javascript code is in an external .js file, but i'm able to execute php code in the HTML code of my page. So I could do something like this:

在 my_file.js 中:

var rows=New Array();

在 HTML 代码中:

<html>
<head>
<script type="text/javascript" src="js/my_file.js"></script>

<script type="text/javascript">
<? foreach ($rows as $row):?>
<? extract($row);?>
rows[<?=$id;?>]['title']="<?=$title;?>";
//And so on
<? endforeach;?>
</script>

推荐答案

为此我倾向于使用 JSON 对象:

I tend to use a JSON object for this:

  • 在服务器端,JSON 对您的数据进行编码:json_encode($data);
  • 在 JavaScript 方面,我编写了一个函数,该函数将 JSON 对象作为参数并将其解包.

当您解压对象时,您可以将数组的内容打印到 <DIV> 标记中,或者打印到页面上任何您想要的位置(jQuery 在这方面做得非常好).

When you unpack the object, you can print the array's contents into a <DIV> tag, or where ever you would like on the page (jQuery does a pretty sweet job of this).

这篇关于在 PHP 和 Javascript 之间传输数组的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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