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) ?

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

3 个解决方案

#1


11

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.

你只能发送一串字节。“发送数组”是通过序列化(对对象进行字符串表示)数组并发送数组来完成的。然后,服务器将解析字符串并从其重新构建内存中的对象。

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

因此,将[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:

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)

Btw, with jQuery you would just do:

顺便说一句,使用jQuery你只需要:

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

更多相关文章

  1. 将php jsonencode数组结果显示为ajax成功函数
  2. 【JavaScript】jQuery+ajax传递json数组(局部响应处理)
  3. 创建一个未排序的数组,其中包含重复元素和唯一元素的总和
  4. js不使用jquery,调用ajax,传递数组,并接受,
  5. 使用jQuery.ajax post函数将javascript数组中的数据传递给服务器
  6. 将JavaScript数组转换成逗号分隔列表的简单方法?
  7. 如何将表列转换为数组?
  8. 如何修复JSON对象的假数组?
  9. 如何从SQL SELECT查询中的c#变量创建jQuery数组

随机推荐

  1. Android学习笔记之开发必备
  2. FFMpeg For Android之Ubuntu下编译
  3. Android设计原则/Android Design Princip
  4. Cocos2d-x移植android加入震动效果
  5. Android自用-----Intent 介绍
  6. Android(安卓)OKHTTP 网络请求出错重连--
  7. Android中shape使用
  8. [android][利用JNI技术在Android中调用、
  9. Android(安卓)Neon
  10. android通过代码来开启和关闭移动网络