Php 带JSON的jQuery Ajax请求
我有一个php文件,在前端提供JSONPhp 带JSON的jQuery Ajax请求,php,jquery,ajax,Php,Jquery,Ajax,我有一个php文件,在前端提供JSON <?php header('Content-type: application/json'); require_once('includes/social-parser.php'); $id = $_POST['id']; $youtube_playlists = $_POST['y']; $twitter_lists = $_POST['t']; $keywords = $_POST['k']; $parser = new socialPar
<?php
header('Content-type: application/json');
require_once('includes/social-parser.php');
$id = $_POST['id'];
$youtube_playlists = $_POST['y'];
$twitter_lists = $_POST['t'];
$keywords = $_POST['k'];
$parser = new socialParser();
$json = $parser->build(json_decode($youtube_playlists), json_decode($twitter_lists), json_decode($keywords),$id);
shuffle($json);
print_r(str_replace('\\/', '/', json_encode($json)));
die();
?>
在我的前端,我使用调用重新请求json:
jQuery.ajax({
url: '/blog/wp-content/themes/blog/social-ajax.php',
type: 'POST',
dataType: 'json',
data: {
y: '<?php echo json_encode($youtube_playlists); ?>',
t: '<?php echo json_encode($twitter_lists); ?>',
k: '<?php echo json_encode($keywords); ?>',
id: '<?php echo $post->ID; ?>'
},
success: function(data, textStatus, xhr) {
jQuery.event.trigger({
type: "social-ajax",
social_object: data
});
},
error: function(xhr, textStatus, errorThrown) {
console.log("Error loading social data");
console.log(xhr);
}
});
jQuery.ajax({
url:“/blog/wp content/themes/blog/social ajax.php”,
键入:“POST”,
数据类型:“json”,
数据:{
y:“”,
t:“,
k:“,
id:“”
},
成功:函数(数据、文本状态、xhr){
jQuery.event.trigger({
键入:“社交ajax”,
社会对象:数据
});
},
错误:函数(xhr、textStatus、errorshown){
日志(“加载社交数据时出错”);
console.log(xhr);
}
});
在某些情况下,它可以工作,但在其他情况下,它在进入错误回调时记录错误,但状态为200。。错误是:
提前感谢在我看来,您正在使您的json无效:
print_r(str_replace('\\/', '/', json_encode($json)));
应该是:
// if $json is not valid json
echo json_encode($json);
或
textStatus
在您的error
函数中的值是多少?statusText是“OK”和errorThrown
值?我不确定errorThrown值是什么意思。。我放了一张打印的xhr对象的屏幕截图。。我希望它在那里。print\r
仅用于调试,不用于正常打印,请使用echo
。另外,您为什么要执行str\u replace('\\/','/',json\u encode($json))?谢谢。。这也是@rocket Hazmat强调的同一个问题,它成功了。。非常感谢:)
// if $json is already valid json
echo $json;