使用jQuery向服务器发送一组数据


Sending an array of data to the server with jQuery

我正在url中向服务器发送CSV列表。这是一个歌姬的列表:

var $array = [];

        oTable.find('td').each(function(){
            $songdata = $(this).data('data');
            $songid = $songdata.songid;
    //The next line is the variable I need to also send along with each songid
            $duration = $songdata.duration;

            $array.push($songid)

            });

这将导致"24,25,32,48,87"被发送到服务器。

然后,我在php脚本中使用以下内容将其转换为数组:

 $songs = $_GET['songid'];
 $songarray = explode(",", $songs);

这很好,我可以正确地访问数据,一切都很好。

然而,我现在需要为每个songid的添加另一个属性。如上所述,我需要将$duration变量添加到发送的数据中,并能够将其转换为阵列服务器端。(或者构建实际阵列客户端也可以)

我该怎么做?

您可以使用它将数组编码为JSON:
http://www.openjs.com/scripts/data/json_encode.php

然后将该字符串发送到您的后端,在那里您可以使用以下代码对其进行解压缩:

$yourarray = json_decode($string)

我会在您的jscript中创建一个数据对象,并将其发送到PHP,然后使用json_decode,然后在PHP 中有一个数据的关联数组

您始终可以使用JSON进行数据序列化/取消实现,就像在jQuery 中序列化为JSON一样

尝试以JSON格式将数组发送到PHP,然后在PHP脚本中执行JSON_decode($var)。

制作一个关联阵列服务器端

$array = new Array();
//add songid as key and duration as value
$array = array_push_assoc($array, $songid, $songduration);

echo json_encode($array);

解析json 后在客户端

$.each(json,function(key,value){
//key will be the songid
//value will be the duration
});