如何使用XMLHttpRequest将数组发送到服务器

时间:2012-08-23 17:19:17

标签: jquery ajax xmlhttprequest

据我所知,使用ajax你可以将数据发送到服务器,但我很困惑发送一个数组发布使用XMLHttpRequest而不是像jQuery这样的库。我的问题是,是否可以使用php将数组发送到XMLHttpRequest以及jQuery如何将数组发送到php,我的意思是jQuery做任何额外的工作来发送数组到服务器(php $ _POST)?

3 个答案:

答案 0 :(得分:13)

你除了一串字节外你不能发送任何东西。 “发送数组”是通过序列化(使对象的字符串表示)数组并发送它来完成的。 然后,服务器将解析字符串并从中重新构建内存中的对象。

因此将[1,2,3]发送给PHP可能会发生这样的情况:

var a = [1,2,3],
    xmlhttp = new XMLHttpRequest;

xmlhttp.open( "POST", "test.php" );
xmlhttp.setRequestHeader( "Content-Type", "application/json" );
xmlhttp.send( '[1,2,3]' ); //Note that it's a string. 
                          //This manual step could have been replaced with JSON.stringify(a)

test.php的:

$data = file_get_contents( "php://input" ); //$data is now the string '[1,2,3]';

$data = json_decode( $data ); //$data is now a php array array(1,2,3)

顺便说一句,你可以使用jQuery:

$.post( "test.php", JSON.stringify(a) );

答案 1 :(得分:1)

这取决于您选择打包数据结构的协议。最常用的2个是XML和JSON。两者都有声明数组的方法:

JSON:['one thing', 'another thing']

XML:<things><thing name='one thing' /><thing name='another thing' /></things>

并且服务器都不会进行任何重要的额外工作。在许多情况下,它实际上会减少工作量,因为您不需要使用命名约定来区分它们。

答案 2 :(得分:0)

您想发送一个jSon对象(可以是一个数组)。如果您使用的是php Send JSON data to PHP using XMLHttpRequest w/o jQuery,请查看此信息。

有关jSon的更多信息:http://json.org/

jQuery jSon示例:JQuery and JSON

相关问题