传递 Javascript 数组 -> PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5035547/
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
Pass Javascript Array -> PHP
提问by switz
Let's say I have a javascript array with a bunch of elements (anywhere from 50-200).
假设我有一个包含一堆元素(从 50 到 200 的任何地方)的 javascript 数组。
I want to send that to PHP (prepared statement) using ajax. Currently, I .load
a php file many times inside of a loop, but I want to convert that into an array and send the array once, loading the PHP file once instead of 50-200 times.
我想使用 ajax 将它发送到 PHP(准备好的语句)。目前,我.load
在一个循环内多次创建一个 php 文件,但我想将其转换为一个数组并发送一次该数组,加载一次 PHP 文件而不是 50-200 次。
array[i] = variable;
array[i] = variable;
回答by Gareth
You could use JSON.stringify(array)
to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']);
in your PHP script to retrieve it.
您可以使用JSON.stringify(array)
JavaScript 对数组进行编码,然后$array=json_decode($_POST['jsondata']);
在 PHP 脚本中使用来检索它。
回答by Alexey Lebedev
AJAX requests are no different from GET and POST requests initiated through a <form>
element. Which means you can use $_GET and $_POST to retrieve the data.
AJAX 请求与通过<form>
元素发起的 GET 和 POST 请求没有区别。这意味着您可以使用 $_GET 和 $_POST 来检索数据。
When you're making an AJAX request (jQuery example):
当您发出 AJAX 请求时(jQuery 示例):
// JavaScript file
elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})
It's (almost) equivalent to posting this form:
它(几乎)等同于发布此表单:
<form action="/test.php" method="post">
<input type="text" name="elements" value="1,2,9,15">
</form>
In both cases, on the server side you can read the data from the $_POST variable:
在这两种情况下,在服务器端,您都可以从 $_POST 变量中读取数据:
// test.php file
$elements = $_POST['elements'];
$elements = explode(',', $elements);
For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.
为了简单起见,我在这里用逗号连接元素。不过,JSON 序列化是一种更通用的解决方案。
回答by Dennis Kreminsky
Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:
这是一个将 js 数组或对象转换为与 php 兼容的数组作为 http get 请求参数发送的函数:
function obj2url(prefix, obj) {
var args=new Array();
if(typeof(obj) == 'object'){
for(var i in obj)
args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
}
else
args[args.length]=prefix+'='+encodeURIComponent(obj);
return args.join('&');
}
prefix is a parameter name.
prefix 是参数名称。
EDIT:
编辑:
var a = {
one: two,
three: four
};
alert('/script.php?'+obj2url('a', a));
Will produce
会产生
/script.php?a[one]=two&a[three]=four
which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.
这将允许您在 script.php 中使用 $_GET['a'] 作为数组。您将需要通过提供从 js 调用 script.php 的 url 来使用您最喜欢的 ajax 引擎。
回答by meagar
So use the client-side loop to build a two-dimensional array of your arrays, and send the entire thing to PHP in one request.
因此,使用客户端循环来构建数组的二维数组,并在一个请求中将整个内容发送到 PHP。
Server-side, you'll need to have another loop which does its regular insert/update for each sub-array.
服务器端,您需要有另一个循环来为每个子数组定期插入/更新。
回答by Reha Ozenc
You can transfer array from javascript to PHP...
您可以将数组从 javascript 传输到 PHP ...
Javascript... ArraySender.html
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
和 PHP 代码... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>