如何使用XMLHtt prequest服务器发送阵列 [英] How to send arrays using XMLHttpRequest to server

查看:100
本文介绍了如何使用XMLHtt prequest服务器发送阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知使用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) );

这篇关于如何使用XMLHtt prequest服务器发送阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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