【发布时间】:2015-03-06 11:01:07
【问题描述】:
我的问题:我不确定如何获取我的 javascript 数组(var 数组)并将其转换为 php 数组。php 数组也应该能够以某种方式获取值。
我已经在 Internet 上搜索了一个解决方案,但我无法在这个示例中真正使用它。我也是 Ajax 的新手,可能有些事情我做得不对。任何帮助和解释将不胜感激。
Script.php
这个文件应该在结果 div 中加载 php 数组。
<div class="test" style="width: 200px height: 50px; background-color: #000;">test</div>
<div class="result" style="width: 200px height: 50px; background-color: yellow; color: #FFF;"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
var array = new Array("test", "test");
$(".test").click(function () {
alert('pressed');
array.push("test");
alert(array);
dataString = array;
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "php.php",
data: {data:dataString},
cache: false,
success: function(){
alert("OK");
}
});
});
});
</script>
php.php
应该将 javascript 数组作为 php 数组回显
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
?>
【问题讨论】:
-
将
true作为第二个参数添加到json_decode()函数。如果您仍然不确定它的结构,请使用print_r()或var_dump()。
标签: javascript php ajax