将PHP Array传递给脚本通过jQuery中的$ .ajax()
问题描述:
我在DOM中有一个很大的数组()。
<div id="array"><?php echo serialize($bigArray); ?></div>
我需要通过我的wordpress主题中的ajax传递这些数据。
$(document).on('click','#somewhere',function(){
var datas = $('#array').html();
$.ajax({
url : ajax_object.ajaxurl,
type : 'post',
data : {
action:'wordpress_action',
array: datas
},
success: function(res) {
console.log(res);
}
});
})
在我的PHP脚本:
add_action('wp_ajax_wordpress_hook', 'my_func');
add_action('wp_ajax_nopriv_wordpress_hook', 'my_func');
function my_func(){
$data = unserialize($_POST['array']);
print_r($data);
die();
}
但这似乎不工作。
有什么建议吗? 如何通过ajax传递php数组? json_encode? PHP会话?
答
在服务器上,您应该将您的$bigArray
以JSON格式嵌入到HTML data attribute中。
PHP的JSON编码功能被称为json_encode()
(不是serialize()
,它确实是something entirely different)。
<div id="array" data-entities="<?php htmlspecialchars(json_encode($bigArray)) ?>">
... regular HTML here ...
</div>
您总是需要调用htmlspecialchars()
当你将数据写入HTML。
在客户端,您可以访问jQuery的.data()
方法的数据属性。
对于通过HTTP传输,您需要将数据重新编码为JSON。 Javascript的JSON编码功能称为JSON.stringify()
。请参阅:How can I use JQuery to post JSON data?
$(document).on('click', '#somewhere', function() {
$.ajax({
url: ajax_object.ajaxurl,
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
action: 'wordpress_action',
array: $('#array').data('entities')
})
}).done(function (res) {
console.log(res);
});
});
答
尝试这样:
echo "<script type=\"text/javascript\">\n";
echo "var strJson = " . json_encode($bigArray) . "\n";
echo "var arrAsObj = JSON.parse(strJson)\n";
echo "</script>\n";
现在你应该可以访问页面上这两个变量。你应该能够在你的ajax文章的请求主体中传递'arrAsObj'。如果遇到问题,请确保该脚本放在html文件中的ajax调用之前。
答
谢谢托默勒格,你的建议我解决了我的错误,但我编辑你的代码。
<div id="array" data-value="<?php echo htmlspecialchars(json_encode($bigArray)) ?>">
$(document).on('click','#somewhere',function(){
var datas = $('#array').data('value');
$.ajax({
url : ajax_object.ajaxurl,
type : 'post',
data : {
action:'wordpress_action',
array: datas
},
success: function(res) {
console.log(res);
}
});
})
然后在PHP脚本:
add_action('wp_ajax_wordpress_hook', 'my_func');
add_action('wp_ajax_nopriv_wordpress_hook', 'my_func');
function my_func(){
$data = $_POST['array'];
print_r($data);
die();
}
这就像我预期
我改变了我的职务。我写错了! – Rock