用一个 AJAX 响应更新两个 div

use*_*676 6 php ajax jquery json

所有,我正在使用 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);
Run Code Online (Sandbox Code Playgroud)

然后在 PHP 端有这样的东西:

echo "This text would go in response text 1";
echo "This text would go in response text 2";
Run Code Online (Sandbox Code Playgroud)

所以基本上我试图在 save_song.php 文件中有多个回声,然后基本上说第一个回声进入第一个 div,第二个回声进入需要更新的第二个 div。知道如何做到这一点吗?

loc*_*zak 5

我会用 json 来做这件事。如果您在 php 中回显关联数组并对其进行 json 编码,jQuery 将自动将 json 字符串转换为对象。

或者,您可以使用某种分隔符(如|&*etc...)回显这两个语句,然后用 javascript 将其拆分,但我认为这是一种更简洁的方法。

//php
echo json_encode(array(
    "responseText1" : "This text would go in response text 1",
    "responseText2" : "This text would go in response text 2"
))

//javascript
$.ajax({
    type: "POST",
    url: "save_song.php",
    dataType: "json",
    data: "song_id=" + song_id + "&love_like_hate=hate",
    success:function(val){
        $("#div_song_id_"+song_id).html(val.responseText1);
        $("#love_it").html(val.responseText2);

    }
});
Run Code Online (Sandbox Code Playgroud)


ent*_*pid 4

您的 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'
    ));
?>
Run Code Online (Sandbox Code Playgroud)

然后你可以在 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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)