所以我使用这个ajax帖子的目的是在wordpress循环中使用一些JS变量,这样我就可以根据ajax帖子中的变量来调用自定义循环。
下面是ajax调用。
$('.collection-more').click(function() {
$.ajax({
type: 'post',
url: 'http://tmet.dev/wp-content/themes/muban-trust/single-collection.php',
data: { "test" : "hello" },
success: function( data ) {
console.log( data );
}
});
})
目前我正在发送硬编码数据。
在我的 single-collection.php 页面中:
<?php
print_r($_POST);
if(isset($POST['filters[Artist]']))
{
$filters_obj = $_POST['filters[Artist]'];
$filters_array = json_decode($filters_obj, TRUE);
for($i = 0; $i < sizeof($filters_array); $i++)
{
echo '<p>h'.$obj->name.'</p>';
}
}
?>
我使用 print_r 只是为了调试问题,目前它返回:
数组()
问题是我无法访问 single-collection.php 中名为“test”的 Json 对象
如何访问它?
提前致谢!
编辑: Firebug 的屏幕截图
最佳答案
从ajax到php: 这是传统的方式
var payload = {
smth1: "name",
smth2: "age"
};
然后调用ajax时
$.ajax({
url: "somephp.php",
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
从 phpPost 到 javascript:
获取post参数的正确方法:
$fields = $_POST['fields'];
$usernameGiven = $fields['smth1'];
$passwordGiven = $fields['smth2'];
以及将 smthn 返回给 javascript 时
$result = array(
"something" => "something",
"something2" => $something2
);
echo json_encode($result);
关于javascript - ajax post 调用后 $_POST 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24953991/