[英]How to pass Javascript array to PHP file using AJAX?
I have to pass a Javascript arry to a PHP file while AJAX call. 我必须在AJAX调用时将Javary arry传递给PHP文件。
Below is my js array: 以下是我的js数组:
var myArray = new Array("Saab","Volvo","BMW");
This JS code has to pass JS array to PHP file using AJAX request and will show count of array. 此JS代码必须使用AJAX请求将JS数组传递给PHP文件,并显示数组的数量。
function ProcessAJAXRequest()
{
$.ajax
({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : myArray},
success: function (data)
{
alert(data);
}
});
}
This myphpfile.php file has to return the count of the array 此myphpfile.php文件必须返回数组的计数
<?php
$myPHPArray = $_POST["myJSArray"];
echo count($myPHPArray);
?>
There is error in PHP file. PHP文件中有错误。 I am getting undefined index: myPHPArray.
我正在得到未定义的索引:myPHPArray。 How should acheive my required functionality?
如何实现我所需的功能?
使用JSON.stringify
将值转换为JSON并将其发送到服务器。
data: JSON.stringify({"id" : 1, "myJSArray" : myArray})
Convert js array in json format by JSON.stringify
通过
JSON.stringify
以JSON格式转换js数组
function ProcessAJAXRequest()
{
$.ajax
({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)},
success: function (data)
{
alert(data);
}
});
}
And In the PHP
use json_decode
function to get value in array 并且在
PHP
使用json_decode
函数获取数组中的值
json_decode($_POST["myJSArray"]);
You could use JSON.stringify(array)
to encode your array in JavaScript, and then use 您可以使用
JSON.stringify(array)
在JavaScript中对数组进行编码,然后使用
$array=json_decode($_POST['jsondata']);
in your PHP script to retrieve it.please check this link 在您的PHP脚本中检索它。请检查此链接
What seems to me is that your array is not available in the function scope: 在我看来,您的数组在函数作用域中不可用:
function ProcessAJAXRequest(){
var myArray = new Array("Saab","Volvo","BMW"); // this has to be in fn scope
$.ajax({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)}, // do the stringify before posting
success: function (data){
alert(data);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.