微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用一个AJAX响应更新两个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字符串:

<?PHP
    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);
        }
    }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐