转让PHP和JavaScript之间的数组的最佳方法 [英] Best way to transfer an array between PHP and Javascript

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

问题描述

所以,我有一个从数据库retreived记录的数组。该阵列格式;

  $行[0] ['身份证'] = 1;
$行[0] ['标题'] ='ABC';
$行[0] [TIME_LEFT'] = 200;


$行[1] ['身份证'] = 2;
$行[1] ['标题'] ='XYZ';
$行[1] ['TIME_LEFT'] = 300;
//等等高达10-20行
 

什么是传递这个数组交给我的javascript code的最佳方法是什么?我想的JavaScript,以便能够遍历所有的记录,并使用id属性,与该ID的一些信息更新的股利。

我的JavaScript code是在外部js文件,但我能在我的网页的HTML code执行PHP code。所以,我可以做这样的事情:

在my_file.js:

  VAR行=新阵列();
 

在HTML code:

 < HTML>
< HEAD>
<脚本类型=文/ JavaScript的SRC =JS / my_file.js>< / SCRIPT>

<脚本类型=文/ JavaScript的>
&LT ;?的foreach($行作为$行):>
&LT ;?提取物($行);?>
行并[d?= $编号;?>] ['标题'] =< = $标题;?>中;
//等等
&LT ;? endforeach;?>
< / SCRIPT>
 

解决方案

我倾向于使用JSON对象这样的:

  • 在服务器端,JSON EN code数据: json_en code($的数据);
  • 在JavaScript端,我写一个函数,它接受一个JSON对象作为参数,并将其解压。

当您打开的对象,就可以打印出数组的内容转换为< D​​IV> 标记,或者你会不会想在页面上(jQuery的做了pretty的这个甜蜜的工作)。

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

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.

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:

In my_file.js:

var rows=New Array();

In HTML code:

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

解决方案

I tend to use a JSON object for this:

  • On the server side, JSON encode your data: json_encode($data);
  • On the JavaScript side, I write a function that takes a JSON object as a parameter and unpack it.

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天全站免登陆