簡體   English   中英

JSON解碼php問題

[英]JSON decode php problems

我有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數組?

您確定要傳遞的數據為json格式嗎

我認為應該

'{"minprice": "min_price", "maxprice":"max_price"}'

您不能僅僅從函數返回ajax返回的值,因為ajax是異步的...在ajax調用完成時,該函數已經返回number_of_estates

使用回調或僅調用一個函數並在其中附加您返回的文本

..
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,所以要小心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM