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

问题描述:

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

$(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:

这样的代码工作:

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

然后我的结果红格为:

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

地发回JSON从你的PHP脚本,而不是HTML(可能是json的值继续aining html ...)。 – jeroen

+0

@ jeroen啊,好的,我不知道json。将看看它 – Jarla

+0

如果这是你所有的代码你得到'未捕获的ReferenceError:id未定义# –

从服务器将数据打包为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

酷!不知道。将立即检查出 – Jarla

+0

有人downvoted。请解释为什么你不介意。对每个人都好! – Iceman

+0

我仍然无法让它在我的代码中运行。我不知道为什么 – Jarla

也是另一种可行的解决方案

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'); 
      } 
     });