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

8 ajax jquery xmlhttprequest

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

Esa*_*ija 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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你可以用jQuery做:

$.post( "test.php", JSON.stringify(a) );
Run Code Online (Sandbox Code Playgroud)

  • @Red是请求正文的原始表示。参见http://php.net/manual/en/wrappers.php.php。例如,考虑普通表单提交,其中有$ _POST [“ key”] ===“ value”`。在这种情况下,“ php:// input”的内容是“ key = value”,这就是PHP用来为您构建$ _POST数组的内容。您需要在这里使用它,因为发布JSON时,php不会填充$ _POST(因为$ _POST仅适用于表单,不适用于JSON)。 (2认同)