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

时间:2012-01-25 10:56:19

标签: 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;
  }

最好的方法是什么?

5 个答案:

答案 0 :(得分:101)

将数据字符串编码为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发送数据时,它需要作为键值对。

因此

data: dataString

错了。而是做:

data: {data:dataString}

答案 1 :(得分:7)

 dataString = [];
   $.ajax({
        type: "POST",
        url: "script.php",
        data:{data: $(dataString).serializeArray()}, 
        cache: false,

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

http://api.jquery.com/serializeArray/

答案 2 :(得分:3)

jQuery ajax()函数中的数据接受匿名对象作为其输入,请参阅documentation。所以你要找的是:

dataString = {key: 'val', key2: 'val2'};
$.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

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

您也可以自己编写POST / GET查询,例如key=val&key2=val2,但是您必须自行处理,这是不切实际的。

答案 3 :(得分:1)

dataString建议数据以字符串格式化(并且可能由字符分隔)。

$data = explode(",", $_POST['data']);
foreach($data as $d){
     echo $d;
}

如果dataString不是字符串,但实际上是一个数组(问题所示),请使用JSON。

答案 4 :(得分:0)

如果您一直尝试发送一个三维数组,并且 jquery正在将其转换为逗号分隔的值>:(,请按照下面的代码进行操作,将提交一个实际的数组改为php,而不是所有逗号都将其分开。

假设您必须附加一个名为myvals的三维数组。

jQuery('#someform').on('submit', function (e) {
    e.preventDefault();
    var data = $(this).serializeArray();

    var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose 
    for (i = 0; i < myvals.length; i++) {
        data.push({
            name: "myvals[]", // These blank empty brackets are imp!
            value: myvals[i]
        });
    }

jQuery.ajax({
    type: "post",
    url: jQuery(this).attr('action'),
    dataType: "json",
    data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
    success: function (r) {
...

执行此操作后,现在放在php

print_r($_POST);

你会得到..

Array
(
    [someinputinsidetheform] => 023
    [anotherforminput] => 111
    [myvals] => Array
        (
            [0] => 21
            [1] => 52
            [2] => 13
            [3] => 24
            [4] => 75
        )
)

请原谅我的语言,但是有Rube-Goldberg个解决方案遍布整个网络,尤其是在SO上,但是它们都不是优雅的解决方案或解决了实际将一维数组发布到php通过ajax发布。不要忘记传播此解决方案。