作者:落叶野 | 来源:互联网 | 2023-12-11 10:07
本文介绍了如何使用jQuery和AJAX来实现动态更新两个div的方法。通过调用PHP文件并返回JSON字符串,可以将不同的文本分别插入到两个div中,从而实现页面的动态更新。
所有,
我正在使用jQuery / AJAX来调用文件,基本上可以保存某人喜欢的歌曲.我正在尝试做类似以下的事情:
var html = $.ajax({
type: "POST",
url: "save_song.php",
data: "song_id=" + song_id + "&love_like_hate=hate",
async: false
}).responseText;
$("#div_song_id_"+song_id).html(responseText1);
$("#love_it").html(responseText2);
然后在PHP方面有这样的事情:
echo "This text would go in response text 1";
echo "This text would go in response text 2";
所以基本上我试图在save_song.php文件中有多个echo,然后基本上说第一个echo进入第一个div,第二个echo进入需要更新的第二个div.知道怎么做吗?
解决方法:
您的PHP代码可以返回一个JSON字符串:
echo json_encode(array(
'test1' => 'This text would go in response text 1',
'test2' => 'This text would go in response text 2'
));
?>
然后你可以在jQuery中解析它:
$.ajax({
type: "POST",
url: "save_song.php",
data: "song_id=" + song_id + "&love_like_hate=hate",
dataType: 'json',
async: false,
success: function(response) {
if (response && response.text1 && response.text2) {
$("#div_song_id_"+song_id).html(response.text1);
$("#love_it").html(response.text2);
}
}
});