简体   繁体   English

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

[英]Send array with Ajax to PHP script

I have array made by function .push .我有由函数.push制作的数组。 In array is very large data.在数组中是非常大的数据。 How is the best way send this to PHP script?将它发送到 PHP 脚本的最佳方式是什么?

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

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

script.php:脚本.php:

  $data = $_POST['data'];

  // here i would like use foreach:

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

How is the best way for this?最好的方法是什么?

Encode your data string into JSON.将您的数据字符串编码为 JSON。

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

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

In your PHP在你的 PHP

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

  // here i would like use foreach:

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

Note笔记

When you send data via POST, it needs to be as a keyvalue pair.当您通过 POST 发送数据时,它需要作为一个键值对。

Thus因此

data: dataString

is wrong.是错的。 Instead do:而是这样做:

data: {data:dataString}

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

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

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

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.如果您一直在尝试发送一维数组并且jquery 正在将其转换为逗号分隔值 >:(然后按照下面的代码将实际数组提交php而不是所有逗号分隔的公牛**它。

Say you have to attach a single dimentional array named myvals .假设您必须附加一个名为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) {
...

Now inside php when you do this当你这样做时,现在在php里面

print_r($_POST);

You will get ..你会得到 ..

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

Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post .请原谅我的语言,但是有很多Rube-Goldberg解决方案散布在整个网络上,特别是在 SO 上,但它们都不是优雅的,也没有解决通过 ajax post 将一维数组实际发布到php的问题 Don't forget to spread this solution.不要忘记传播这个解决方案。

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation . jQuery ajax()函数中的数据接受匿名对象作为其输入,请参阅文档 So example of what you're looking for is:所以你正在寻找的例子是:

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

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

You may also write POST/GET query on your own, like key=val&key2=val2 , but you'd have to handle escaping yourself which is impractical.您也可以自己编写 POST/GET 查询,例如key=val&key2=val2 ,但您必须自己处理逃避,这是不切实际的。

dataString suggests the data is formatted in a string (and maybe delimted by a character). dataString 表明数据格式为字符串(并且可能由字符分隔)。

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

if dataString is not a string but infact an array (what your question indicates) use JSON.如果 dataString 不是字符串而是实际上是数组(您的问题所指的),请使用 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM