简体   繁体   English

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

[英]Passing JavaScript array to PHP through jQuery $.ajax

I want to manipulate a JavaScript array in PHP. 我想在PHP中操作JavaScript数组。 Is it possible to do something like this? 可以这样做吗?

$.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? 我尝试这个时脚本没有完成...我该如何解决?

data: { activitiesArray: activities },

That's it! 而已! Now you can access it in PHP: 现在您可以在PHP中访问它:

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

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 here for details. 详情请见此处

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. 您将不得不向PHP大师询问如何在服务器上处理此问题。 I think other answers here intimate a solution. 我认为其他答案在这里是一个解决方案。

Data can be returned from the server in a similar way. 可以以类似的方式从服务器返回数据。 Ie you can turn it back into an object. 即你可以把它变回一个物体。

var myObject = JSON.parse(myJSONString);

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); var st = JSON.stringify(your_object);将你的javascript对象(json)字符串化var st = JSON.stringify(your_object);

  2. Pass your POST data as "string" (maybe using jQuery: $.post('foo.php',{data:st},function(data){... }); 将您的POST数据作为“字符串”传递(可能使用jQuery: $.post('foo.php',{data:st},function(data){... });

  3. Decode your data on the server-side processing: $data = json_decode($_POST['data']); 在服务器端处理解码数据: $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). 关联数组(javsacript对象)作为php对象(类)处理。 To access them just do it like classes: $foo->bar . 要访问它们就像类: $foo->bar

I should be like this: 我应该是这样的:

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

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;
}

Use the JQuery Serialize function 使用JQuery Serialize函数

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. Serialize通常用于准备要发布到服务器的用户输入数据。 The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks. 序列化数据采用标准格式, 几乎与所有服务器端编程语言和框架兼容

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';

This is because PHP reads your value as a string. 这是因为PHP将您的值读取为字符串。 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中执行此操作:

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

The last line splits string into bits after every comma. 最后一行在每个逗号后将字符串拆分为多个位。 Now $activitiesArray is also an array. 现在$ activitiesArray也是一个数组。 It works even if there is no comma (only one element in your javascript array). 即使没有逗号(javascript数组中只有一个元素),它也能正常工作。

Happy coding! 快乐的编码!

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

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