如何通过Ajax将数据发送到不同的元素?

时间:2017-04-20 09:37:49

标签: php jquery ajax

的script.js

 $(document).on("click", ".send", function (event) {
   $.ajax({
            url: "update.php",
            data: {
               id: id,
            },
            type: "POST",
            success: function (data) {
                $(".blue").html(data);
                $(".red).html(data);
            }
        })
 });

update.php

echo "this text should go to blue";
echo "this text should go to red";

的index.php

<button class="send">Send</button>
<div class="blue"></div>
<div class="red"></div>

在一个Ajax请求中,我想将数据发送到两个不同的div。我不知道如何解决这个问题。或者,如果这可能吗?我尝试了两个不同的Ajax请求。但是因为我需要从数据库中获取数据,这会导致冲突。

根据建议更新代码:

   $(".send").click(function(){
      $.ajax({
            url: "update.php",
            data: {},
            type: "POST",
            success: function (data) {
                $(".blue").html(data.blue);
                $(".red").html(data.red);
                  alert("success");
            }
        })
});

update.php

$array['blue'] = "blue content";
$array['red'] = "red content";
header('Content-type: application/json');
echo json_encode($array);

更新:

像这样代码正在运行:

Update.php

$array['blue'] = "blue content";
$array['red'] = "red content";
//header('Content-type: application/json');
echo json_encode($array);

素文字:

 $.ajax({
            url: "update.php",
            data: {},
            type: "POST",
            success: function (data) {
                //$(".blue").html(data.blue);
                //$(".red").html(data.red);
                $(".red").html(data);
                  alert("success");
            }
        })

然后我在red div中的结果是:

{"blue":"blue content","red":"red content"}

2 个答案:

答案 0 :(得分:3)

从服务器打包数据作为JSON,并将其解压缩到客户端。

简单示例:

update.php

$array['blue'] = "blue content";
$array['red'] = "red content";
header('Content-type: application/json');
echo json_encode($array);

的script.js

$(document).on("click", ".send", function (event) {
   $.ajax({
            url: "update.php",
            data: {
               id: id,
            },
            type: "POST",
            success: function (data) {
                $(".blue").html(data.blue);
                $(".red").html(data.red);
            }
        })
 });

答案 1 :(得分:0)

另一种可行的解决方案

var jsonUrl = 'update.php';
        $.ajaxSetup({
            cache: false
        });
        $.ajax({
            type: 'GET',
            url: jsonUrl,
            data: {},
            dataType: 'json',
            success: function (data) {
                $('.blue').html(data.blue);
                $('.red').html(data.red);
            },
            error: function (xhr) {
                $('.red').html('error fetching data');
            }
        });
相关问题