如何使用XMLHtt prequest服务器发送阵列阵列、如何使用、服务器、prequest

2023-09-10 16:52:08 作者:有她你就足够

据我所知使用AJAX可以将数据发送到服务器,但我感到困惑发送阵列后使用 XMLHtt prequest 不是像jQuery的任何图书馆。我的问题是这样的,是可以发送一个数组 PHP 使用 XMLHtt prequest 如何做的jQuery 发送数组PHP的,我的意思是它的jQuery做任何额外的工作来发送一个数组服务器(PHP $ _ POST)?

As I know using ajax you can send data to the server but I'm confused about sending an array to post using XMLHttpRequest not any library like jQuery. My question is that, is that possible to send an array to php using XMLHttpRequest and how does jQuery send an array to php, I mean does jQuery do any additional work to send an array to server (php $_POST) ?

推荐答案

那么你将无法发送任何东西,但字节的字符串。 发送阵列是由序列化(使串重新对象presentation)数组,并发送该做的。 然后,服务器将分析该字符串并从中重新构建内存中的对象。

Well you cannot send anything but a string of bytes. "Sending arrays" is done by serializing (making string representation of objects) the array and sending that. The server will then parse the string and re-build in-memory objects from it.

所以发送 [1,2,3] 切换到PHP可能发生的像这样:

So sending [1,2,3] over to PHP could happen like so:

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

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你只是做:

Btw, with jQuery you would just do:

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