我通过ajax将数组从一个页面发送到另一个页面。为此,我使用了JSON对象。我可以发送,但无法在ajax页面中捕获。请帮助我如何获取数组值。javascript:
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "ajaxpage.php",
data: {data : jsonString},
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
PHP页面:
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
请在这方面帮助我。我被困在这里
如果您想将JSON解码为关联数组,您应该在json_decode
:中指定
更换
$data = json_decode(stripslashes($_POST['data']));
带
$data = json_decode(stripslashes($_POST['data']), true);
更多信息请参见json_decode
参考
另外,dataString
可能已经是一个JSON字符串了吗?
我想这就是你想要的,我已经尝试过了,它有效
在您的php:中
<?php
$data = ($_POST['data']);
foreach($data as $d){
echo stripslashes($d);
}
?>
在您的jsvascript/jquery中:
<script>
$(document).ready(function(){
$('a').on('click',function(){
var dataString = {
'id':'1',
'name':'peter parker',
'age':'unknown',
'role':'spiderman'
}
$.ajax({
url: "<?php echo $this->webroot;?>test_1.php",
data: {'data':dataString},
type: "POST",
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
})
})
</script>
在您的html 中
<a href="javascript:void(0);">Click Me</a>
<div id="test"></div>