我是这一切的新手,对于任何明显的错误我深表歉意。
我正在尝试使用Javascript的ajax调用从数据库中选择一个随机电影,使用有关该电影的信息创建一些html,然后还将信息数组发送回一个变量中。我正在使用多个php echo语句来执行此操作。当然,问题在于echo语句相互粘贴,因此JSON无法解析它。
Ajax呼叫:
var getOutput = function() {
var movies = [];
$.ajax({
url:'on_movie_click.php',
success: function (response) {
$('#selection_area').html(response.responseText);
console.log(response); #troubleshooting
movies = JSON.parse(response);
},
error: function () {
$('#selection_area').html('There was an error!');
}
});
return movies;
}
php代码:
//Getting info from database above
$index = [$movie_a,$movie_b];
echo json_encode($index);
echo "<div id='movie_a'><div id='movie_a_title'>$movie_a[1] </div><div id='movie_a_year'>($movie_a[2])</div></div>";
echo "<div id='movie_b'><div id='movie_b_title'>$movie_b[1] </div><div id='movie_b_year'>($movie_b[2])</div></div>";
ajax调用中的console.log会正确输出存储的数组$ index,但同时也添加了两个<div...
语句。因此,JSON.parse引发错误。
有没有办法将变量($ index)都存储回javascript变量(var电影),同时又使其他两个echo语句使用相同的ajax调用来更新网页?
编辑:感谢kuma DK的工作。
您不需要html标记的回声即可更改页面。只需通过javascript使用dom操作即可:
//first a function to create the movie div
//for the div id's you hand over the array index
function newMovieDiv(movie, index){
//define the outer div
var movieDiv = $("<div>").attr('id', 'movie' + index),
//define the title div
movieTitle = $("<div>").attr('id', 'movie' + index + 'title').text(movie[0]),
//define the year div
movieYear = $("<div>").attr('id', 'movie' + index + 'year').text("(" + movie[1] + ")");
//put it all together and return it
return movieDiv.append(movieTitle, movieYear);
}
然后,您将电影阵列并循环遍历。使用当前项及其索引调用函数,并将返回值保存在变量movieItem中。然后将其附加到要插入的任何元素。
movies.forEach(function(item) {
var movieItem = newMovieDiv(item, movies.indexOf(item));
$("#movieList").append(movieItem);
});
当然,您必须适应您的电影json。但是通过这种方式,您仅应请求从服务器发送电影json,而无需在每个php调用中发送标记信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句