2012-07-21 37 views
5

我已經設置了一些ajax,我現在只是測試它,其背後的想法很多是將一些數據從下拉框發送到一個php腳本,做一些計算然後返回結果,它做得很好,並返回結果,但現在,而不是隻發回一個結果和輸出,我想發回多個結果並輸出它們,我能夠發送多個數據到php腳本,所以我是當然我可以發送多個回來。通過AJAX通過PHP發送多個結果

無論如何,它只發回第一個結果,而不是其餘。

這裏是AJAX

<script> 
$("document").ready(function(){ 

    $(".add_extension").change(function(){ 


     var m = document.getElementById('meter_square'); 
     var meter_square = m.options[m.selectedIndex].value; 

     var s = document.getElementById('story_height'); 
     var story_height = s.options[s.selectedIndex].value; 

    $.ajax({ 
      type: "GET", 
      url: "script.php", 
      data: { meter_square: meter_square, story_height: story_height }, 
      dataType: "json", 
      statusCode: { 
       200: function (result, result2) 
       { 
        $("#expected_gain").html(result.value); 
       $("#house_price").html(result2.value2); 
       } 

      } 
     }); 
}) 
}); 
</script> 

,這裏是PHP腳本

<?php 

$meter_square = $_GET["meter_square"]; 
$story_height = $_GET["story_height"]; 


$result = $meter_square + $story_height; 
$result2 = $meter_square * $story_height; 

echo json_encode(array("value" => $result, "value2" => $result2)); 

?> 

你可以看到,我已經嘗試給它從我的想法可能會奏效,如果去你需要任何其他代碼或要我刪除我添加的代碼不起作用,然後讓我知道。

感謝所有和任何幫助

+0

爲什麼你需要做加法和乘法在PHP? JS是完全有能力的 – Martin 2012-07-21 16:14:07

+0

我只是使用它作爲測試部分來讓ajax首先工作,php腳本將會非常大,所以我在 – Arken 2012-07-21 16:17:18

+0

之後就可以了,只需檢查一下;)我看到你已經有了它解決了反正:) – Martin 2012-07-21 17:01:47

回答

7

你只會收到一個響應對象:

function (response) { 
    $("#expected_gain").html(response.value); 
    $("#house_price").html(response.value2); 
} 
+0

輝煌,完美的作品,這項工作,如果我想發回6不同的結果? – Arken 2012-07-21 16:19:24

+0

它的工作原理大致相同:例如,如果你想發回數組,例如'array(「width」=> 10,「height」=> 5,「depth」=> 3)',你會能夠使用'response.width','response.height'和'response.depth'。 – 2012-07-21 16:21:23

+0

確定輝煌,感謝您的全力幫助 – Arken 2012-07-21 16:22:16

4

試試這個。認爲它會有所幫助。無需使用狀態碼,如果ü要使用唯一的成功案例

$.ajax({ 
     type: "GET", 
     url: "script.php", 
     data: { meter_square: meter_square, story_height: story_height }, 
     dataType: "json", 
     success: function(data){ 
      $("#expected_gain").html(data.value); 
      $("#house_price").html(data.value2); 
     } 
    }); 
+0

良好的「成功」而不是狀態代碼。 +1! – Linuxios 2012-07-21 16:31:28