【问题标题】:Sending back multiple results from PHP via AJAX通过 AJAX 从 PHP 发回多个结果
【发布时间】:2012-07-20 13:57:25
【问题描述】:

我已经设置了一些 ajax,我现在正在测试,它背后的想法几乎是将一些数据从下拉框中发送到 php 脚本,进行一些计算然后返回结果,它做得很好并返回结果,但现在不仅仅是发回一个结果并输出,我想发回多个结果并输出它们,我能够将多个数据发送到 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));

 ?>

您可以看到我已经尝试过尝试使用我认为可行的方法,如果您需要任何其他代码或希望我删除我添加的不起作用的代码,请告诉我。

感谢大家的帮助

【问题讨论】:

  • 为什么需要在PHP中做加法和乘法? JS 很能干
  • 我只是把它作为一个测试部分来让ajax首先工作,php脚本会很大,所以我在做之后
  • 好的,只是检查一下;)我知道你已经解决了:)

标签: php javascript jquery ajax json


【解决方案1】:

您只会收到一个响应对象:

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

【讨论】:

  • 太棒了,效果很好,如果我想发回 6 个不同的结果,这能行吗?
  • 它的工作原理大致相同:如果你想发回,例如array( "width" =&gt; 10, "height" =&gt; 5, "depth" =&gt; 3 ),你可以使用response.widthresponse.heightresponse.depth .
【解决方案2】:

试试这个。认为它会有所帮助。如果您只使用成功案例,则无需使用状态码

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

【讨论】:

  • success 代替状态码很好。 +1!
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多