在JavaScript中将字符串转换为数组 [英] Convert String to Array in JavaScript

查看:130
本文介绍了在JavaScript中将字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的PHP字符串:

I have a PHP String like this:

$string = 'a => 1 , b => 2 , c => 3 , d => 4';

我从数据库中的数据中构建了

,其中每个"x => y"代表x和y之间的关联关系.

which I have built from data from a database, where each "x => y" represents an associative relationship between x and y.

然后我将这个字符串传输到html文档(JQuery),并尝试在JavaScript中用它制作一个数组,以便我可以在客户端进行处理.

I am then transferring this string to the html document (JQuery) and attempting to make an array out of it in JavaScript, so that I may process on the client side.

问题:

是否可以从字符串创建JavaScript数组?
例如,我需要能够通过调用'alert(array["c"]);'或类似方法来检索数组中的值.

Is it possible to create a JavaScript Array out of a string?
For example I need to be able to retrieve the values in the array by calling 'alert(array["c"]);' or something similar.

注意-随时根据需要更改上述字符串($ string)的语义.

NOTE - feel free to alter the semantics of the above string ($string) as necessary.

任何帮助表示赞赏的人....

Any help appreciated guys....

推荐答案

PHP代码

(例如,一个文件,例如array.php):

PHP Code

(for instance, a file, like array.php):

$array=array(
    'a'=>'I am an A',
    'param2_customname'=>$_POST['param2'],
    'param1'=>$_POST['param1']
);
echo json_encode($array);


jQuery代码:

$.post('array.php', {'param1': 'lol', 'param2': 'helloworld'}, function(d){
   alert(d.a);
   alert(d.param2_customname);
   alert(d.param1);
},'json');

您可以将其用于数组,请记住每次请求末尾的'json'标签.

You can use this for arrays, remember the 'json' tag at the end of the request everytime.

这篇关于在JavaScript中将字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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