php - 使用 Ajax 将数组发送到 PHP 脚本

标签 php javascript jquery ajax

我有一个由函数 .push 创建的数组。在数组中是非常大的数据。将其发送到 PHP 脚本的最佳方式是什么?

   dataString = ??? ; // array?
   $.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

script.php:

  $data = $_POST['data'];

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

最好的方法是什么?

最佳答案

将您的数据字符串编码为 JSON。

dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

在您的 PHP 中

$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

注意

当您通过 POST 发送数据时,它需要作为键值对。

这样

数据:dataString

错了。而是这样做:

数据:{data:dataString}

关于php - 使用 Ajax 将数组发送到 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9001526/

相关文章:

php - PHP 中的段错误,使用 SOAP 连接到 SalesForce

php - 循环遍历 POST 数组以进行数据库插入

javascript - 从 Angular 服务获取最终数据

javascript - 如何定位相机,使物体在屏幕上始终具有相同的像素宽度和高度?

javascript - 如何从以下代码中的众多类似按钮中选择被单击的按钮?

javascript - Angularjs 过滤器回调

php - 我遇到过这种语法 : var == "" ? "-": var. 有人可以解释一下吗?

javascript - NodeJS-发送简单响应

javascript - 如何根据数据属性值应用背景颜色

php - 从客户端 javascript 页面接收数组