0

我有 index.php 并且在解码 json 数组时遇到问题..请帮助我是新手..

<script>
$(document).ready(function () {
    $("#slider_price").slider({
        range: true,
        min: 0,
        max: 100,
        step: 1,
        values: [0, 100],
        slide: function (event, ui) {
            $("#app_min_price").text(ui.values[0] + "$");
            $("#app_max_price").text(ui.values[1] + "$");
        },
        stop: function (event, ui) {
            var nr_total = getresults(ui.values[0], ui.values[1]);

            $("#results").text(nr_total);
        },
    });
    $("#app_min_price").text($("#slider_price").slider("values", 0) + "$");
    $("#app_max_price").text($("#slider_price").slider("values", 1) + "$");
});

function getresults(min_price, max_price) {
    var number_of_estates = 0;
    $.ajax({
        type: "POST",
        url: 'search_ajax.php',
        dataType: 'json',
        data: {
            'minprice': min_price,
            'maxprice': max_price
        },
        async: false,
        success: function (data) {
            number_of_estates = data;
        }
    });
    return number_of_estates;
}

和 search_ajax.php

<?php
 require_once('includes/commonFunctions.php');
// take the estates from the table named "Estates"
if(isset($_POST['minprice']) && isset($_POST['maxprice']))
{
 $minprice  = filter_var($_POST['minprice'] , FILTER_VALIDATE_INT);  
 $maxprice  = filter_var($_POST['maxprice'] , FILTER_VALIDATE_INT); 
 $query = mysql_query("SELECT * FROM cars WHERE min_range >= $minprice AND max_range     <= $maxprice");

$rows = array();
while($r = mysql_fetch_assoc($query)) {
  $rows[] = $r;
}

echo json_encode($rows);

}
?>

问题是我只想在特定的div“number_results”中打印$rows ..如何解码那个json数组?

4

2 回答 2

0

你确定你传递的数据是json格式吗

我认为应该是

'{"minprice": "min_price", "maxprice":"max_price"}'
于 2013-10-23T10:45:08.250 回答
0

您不能只从函数返回 ajax 返回值,因为 ajax 是异步的……在number_of_estatesajax 调用完成时,该函数已经返回。

使用回调或只是调用一个函数并将返回的文本附加到那里

..
stop: function( event, ui ) {
  getresults(ui.values[0], ui.values[1]);
},
...

function getresults(min_price, max_price)
{ 
   var number_of_estates = 0;
   $.ajax({
     type: "POST",
     url: 'search_ajax.php',
     dataType: 'json',
     data: {'minprice': min_price, 'maxprice':max_price},
     async: false,
     success: function(data)
     {
        number_of_estates = data;
        $("#results").text(number_of_estates);
     }
  });
 }

但是每次停止功能发生时都会调用ajax,所以要小心。

于 2013-10-23T10:45:25.873 回答