2017-04-20 80 views
1

的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未定義# –

回答

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

酷!不知道。將立即檢查出 – Jarla

+0

有人downvoted。請解釋爲什麼你不介意。對每個人都好! – Iceman

+0

我仍然無法讓它在我的代碼中運行。我不知道爲什麼 – Jarla

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