2012-07-21 61 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