[英]Load Json data with AJAX and PHP
我正在尝试使用Ajax加载json数据,但是它不起作用。 每次ajax都调用错误函数,而不调用成功函数。
我的AJAX通话:
$(document).on("click", "#myMovies .btn-update", function() {
var id = $(this).parent().data("id");
$.ajax({
url : 'index.php',
type : 'POST',
dataType: 'json',
data : 'id=' + id + '&action=update',
success : function(data){
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},
error : function(jqXHR, textStatus, errorThrown){
console.log("error");
alert(textStatus);
alert(errorThrown);
}
});
});
index.php的有趣部分:
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array, JSON_FORCE_OBJECT );
}
有人知道我的错误在哪里吗? 谢谢您的回答。
我认为问题出在'JSON_FORCE_OBJECT'选项。 请求期望的数据类型是json字符串。 将JSON_FORCE_OBJECT添加到json_encode函数时,json字符串对该请求无效。
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array);
die();
}
还将 json的解析器添加到您的javascript( parseJSON ):
success : function(data){
data = $.parseJSON(data);
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.