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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9001526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:21:11  来源:igfitidea点击:

Send array with Ajax to PHP script

phpjavascriptjqueryajax

提问by Paul Attuck

I have array made by function .push. In array is very large data. How is the best way send this to PHP script?

我有由函数.push制作的数组。在数组中是非常大的数据。将它发送到 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?

最好的方法是什么?

回答by xbonez

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

data: dataString

is wrong. Instead do:

是错的。而是这样做:

data: {data:dataString}

data: {data:dataString}

回答by John x

 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/

回答by Vyktor

Data in jQuery ajax()function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:

jQueryajax()函数中的数据接受匿名对象作为其输入,请参阅文档。所以你正在寻找的例子是:

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,但您必须自己处理逃避,这是不切实际的。

回答by RvdK

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。

回答by Mohd Abdul Mujib

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 submittedto phpand 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 phpwhen 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-Goldbergsolutions 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 phpvia ajax post. Don't forget to spread this solution.

请原谅我的语言,但是有很多Rube-Goldberg解决方案散布在整个网络上,特别是在 SO 上,但没有一个是优雅的,也没有解决通过 ajax post实际发布一维数组php的问题。不要忘记传播这个解决方案。