通过 jQuery $.ajax 将 JavaScript 数组传递给 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2013728/
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-22 22:23:52  来源:igfitidea点击:

Passing JavaScript array to PHP through jQuery $.ajax

phpjavascriptjqueryajax

提问by krx

I want to manipulate a JavaScript array in PHP. Is it possible to do something like this?

我想在 PHP 中操作 JavaScript 数组。有可能做这样的事情吗?

$.ajax({
       type: "POST",
       url: "tourFinderFunctions.php",
       data: "activitiesArray="+activities,
       success: function() {
            $("#lengthQuestion").fadeOut('slow');
       }
    });

Activities is a single dimensional array like:

活动是一个一维数组,如:

var activities = ['Location Zero', 'Location One', 'Location Two'];

The script does not complete when I try this... How can I fix it?

当我尝试这个时脚本没有完成......我该如何修复它?

回答by Valentin Golev

data: { activitiesArray: activities },

That's it! Now you can access it in PHP:

就是这样!现在您可以在 PHP 中访问它:

<?php $myArray = $_REQUEST['activitiesArray']; ?>

回答by jvenema

You'll want to encode your array as JSON before sending it, or you'll just get some junk on the other end.

您需要在发送数组之前将其编码为 JSON,否则您只会在另一端得到一些垃圾。

Since all you're sending is the array, you can just do:

由于您发送的只是数组,因此您可以执行以下操作:

data: { activities: activities }

which will automatically convert the array for you.

这将自动为您转换数组。

See herefor details.

有关详细信息,请参见此处

回答by James Wiseman

You need to turn this into a string. You can do this using the stringify method in the JSON2 library.

你需要把它变成一个字符串。您可以使用 JSON2 库中的 stringify 方法执行此操作。

http://www.json.org/

http://www.json.org/

http://www.json.org/js.html

http://www.json.org/js.html

The code would look something like:

代码如下所示:

var myJSONText = JSON.stringify(myObject);

So

所以

['Location Zero', 'Location One', 'Location Two'];

Will become:

会变成:

"['Location Zero', 'Location One', 'Location Two']"

You'll have to refer to a PHP guru on how to handle this on the server. I think other answers here intimate a solution.

您必须参考 PHP 专家来了解如何在服务器上处理此问题。我认为这里的其他答案暗示了一个解决方案。

Data can be returned from the server in a similar way. I.e. you can turn it back into an object.

可以以类似的方式从服务器返回数据。即你可以把它变回一个对象。

var myObject = JSON.parse(myJSONString);

回答by lu1s

I know it may be too late to answer this, but this worked for me in a great way:

我知道现在回答这个问题可能为时已晚,但这对我很有用:

  1. Stringify your javascript object (json) with var st = JSON.stringify(your_object);

  2. Pass your POST data as "string" (maybe using jQuery: $.post('foo.php',{data:st},function(data){... });

  3. Decode your data on the server-side processing: $data = json_decode($_POST['data']);
  1. 使用字符串化您的 javascript 对象 (json) var st = JSON.stringify(your_object);

  2. 将您的 POST 数据作为“字符串”传递(也许使用 jQuery: $.post('foo.php',{data:st},function(data){... });

  3. 在服务器端处理中解码您的数据: $data = json_decode($_POST['data']);

That's it... you can freely use your data.

就是这样......您可以自由使用您的数据。

Multi-dimensional arrays and single arrays are handled as normal arrays. To access them just do the normal $foo[4].

多维数组和单数组作为普通数组处理。要访问它们,只需执行正常的$foo[4].

Associative arrays (javsacript objects) are handled as php objects (classes). To access them just do it like classes: $foo->bar.

关联数组(javsacript 对象)作为 php 对象(类)处理。要访问它们就像类一样:$foo->bar.

回答by masterdany88

I should be like this:

我应该是这样的:

$.post(submitAddress, { 'yourArrayName' : javaScriptArrayToSubmitToServer },
  function(response, status, xhr) {
    alert("POST returned: \n" + response + "\n\n");
  })

回答by chelista

Use the PHP built-in functionality of the appending the array operand to the desired variable name.

使用将数组操作数附加到所需变量名称的 PHP 内置功能。

If we add values to a Javascript array as follows:

如果我们将值添加到 Javascript 数组,如下所示:

acitivies.push('Location Zero');
acitivies.push('Location One');
acitivies.push('Location Two');

It can be sent to the server as follows:

它可以发送到服务器,如下所示:

$.ajax({        
       type: 'POST',
       url: 'tourFinderFunctions.php',
       'activities[]': activities
       success: function() {
            $('#lengthQuestion').fadeOut('slow');        
       }
});

Notice the quotes around activities[]. The values will be available as follows:

注意活动[]周围的引号。这些值将如下可用:

$_POST['activities'][0] == 'Location Zero';
$_POST['activities'][1] == 'Location One';
$_POST['activities'][2] == 'Location Two';

回答by I.Tyger

This worked for me:

这对我有用:

$.ajax({
    url:"../messaging/delete.php",
    type:"POST",
    data:{messages:selected},
    success:function(data){
     if(data === "done"){

     }
     info($("#notification"), data);
    },
    beforeSend:function(){
         info($("#notification"),"Deleting "+count+" messages");
    },
    error:function(jqXHR, textStatus, errorMessage){
        error($("#notification"),errorMessage);
    }
});

And this for your PHP:

这适用于您的PHP

$messages = $_POST['messages']
foreach($messages as $msg){
    echo $msg;
}

回答by Gazzer

Use the JQuery Serialize function

使用 JQuery 序列化函数

http://docs.jquery.com/Ajax/serialize

http://docs.jquery.com/Ajax/serialize

Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languagesand frameworks.

序列化通常用于准备要发布到服务器的用户输入数据。序列化数据采用标准格式,与几乎所有服务器端编程语言和框架兼容

回答by Hawthorn

This is because PHP reads your value as a string. If I don't want to pass my data as an object (like in the previous answers, which are also fine), I just do this in my PHP:

这是因为 PHP 将您的值作为字符串读取。如果我不想将我的数据作为对象传递(就像在前面的答案中一样,也很好),我只是在我的 PHP 中执行此操作:

 $activitiesString = $_POST['activitiesArray'];
 $activitiesArray = (explode(",",$activitiesString));

The last line splits string into bits after every comma. Now $activitiesArray is also an array. It works even if there is no comma (only one element in your javascript array).

最后一行在每个逗号之后将字符串拆分为位。现在 $activityArray 也是一个数组。即使没有逗号(您的 javascript 数组中只有一个元素),它也能工作。

Happy coding!

快乐编码!