【问题标题】:Update two divs with one AJAX response用一个 AJAX 响应更新两个 div
【发布时间】:2012-02-17 18:42:47
【问题描述】:

所有, 我正在使用 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 文件中有多个回声,然后基本上说第一个回声进入第一个 div,第二个回声进入需要更新的第二个 div。知道怎么做吗?

【问题讨论】:

    标签: php ajax json jquery


    【解决方案1】:

    我会用 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);
    
        }
    });

    【讨论】:

    • +1 json 绝对是如何做到这一点的方式。我还会添加一些更详细的解释和示例,例如net.tutsplus.com/tutorials/javascript-ajax/…(第二个块,谷歌搜索“jquery ajax json 示例”后的第一个工作页面)
    • 很好,谢谢,真的不知道有什么好的ajax。感谢您的链接
    • @locrizak 感谢您的代码。我试图这样做,但是当我尝试执行 alert(val.responseText1) 时,它说它是未定义的。知道为什么会这样吗?
    • 尝试 console.log(val) 并尝试以这种方式调试它。如果它仍然不起作用,那么您在 php 端的回显方式可能存在问题
    【解决方案2】:

    你的 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);
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 2020-09-23
      • 2013-08-06
      • 2021-04-09
      相关资源
      最近更新 更多