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

标签 php jquery ajax

脚本.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);
            }
        })
 });

更新.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");
            }
        })
});

更新.php

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

更新:

像这样,代码正在运行:

更新.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");
            }
        })

那么我在红色div中的结果是:

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

最佳答案

从服务器将数据打包为 JSON,然后在客户端解包。

简单示例:

更新.php

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

脚本.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);
            }
        })
 });

关于php - 如何通过 Ajax 将数据发送到不同的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43515734/

相关文章:

php/sql - 在多个字段上插入相同的值

php - 如何为 PHP/MySQL 应用程序自动迁移(架构和数据)

php - CodeIgniter 缓存驱动程序忽略备份适配器

javascript - 使用 $.each 后如何更新数组的索引

jQuery:如何 AJAX 化 WordPress 搜索?

javascript - 无法使用ajax渲染img标签

php - 使用此内部连接获取数据时遇到问题 (MYSQL/PHP)

javascript - 如何将图像高度设置为具有相同类名的div的其他部分

php - 使用 jquery (ajax) 和 php 的上一个和下一个日期

javascript - 我想使用 javascript 或 jquery 更改内容