[英]Pass multiple arrays from PHP through jQuery AJAX to Javascript
[英]how to pass a Javascript array from Javascript to PHP through Jquery/Ajax?
我想知道如何通过Jquery/Ajax
将Javascript
数组从Javascript
传递到PHP
。 实际上,我创建了两个文件: t1.html
和moslem3.php
。 每个文件的代码如下:
t1.html的代码:
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: table
});
});
</script>
</body>
</html>
moslem3.php的代码:
<?php
$myArray = $_REQUEST['table'];
echo $myArray;
?>
文件moslem3.php
显示以下消息:
Notice: Undefined index: table in C:\wamp\www\test1\moslem3.php on line 2
所以我的问题是:这到底是哪里错了?..有人有什么主意吗?
提前致谢。
PHP本质上不了解所使用的JavaScript变量,例如var table
。 它对$.ajax()
请求的见解仅限于data
结构。
因此,为了使PHP知道$_REQUEST
的'table'
参数, data
需要将其包含为命名值:
data: { table: table }
这将data
定义为Object
,并且属性table
通过相同的名称分配给变量的值。
您可以使用$.param()
见证差异,而$.ajax()
使用:
var table = ["actor", "subject", "object"];
console.log($.param(table));
// "undefined=&undefined=&undefined="
console.log($.param({ table: table }));
// "table%5B%5D=actor&table%5B%5D=subject&table%5B%5D=object"
更改jQuery
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: {t_name:table },
success:function(data){
console.log(data);
}
});
});
</script>
更改moslem3.php
<?php
$myArray = $_REQUEST['t_name'];
print_r($myArray);
?>
输出:
尝试这个 :
$.ajax({
type : "POST",
url: 'moslem3.php',
cache:false,
async:true,
global:false,
data : {
"table": table }
}).done(function(msg) {
alert(msg);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.