无法在jQuery中解析响应

时间:2014-09-15 19:09:21

标签: php jquery ajax json

我从PHP脚本中得到以下响应。

PHP:

<?php
$con = mysqli_connect("localhost","root","pass","products");

if(mysqli_connect_errno()) {
    echo "Failed to connect database, please check with your administrator. Error is <br />" . mysqli_connect_errno();
}   

$cat = $_POST['cat'];
$text = "this is from php server";
$json = array();
$html = ''; 
if ($cat == 'designer'){
    $query = " select * from shirts where category_1 = '$cat'";
    $result = mysqli_query($con, $query);

    while ($row = mysqli_fetch_array($result))
    {

        $html .= "<div class='des-result'>" . $row['code'] ."</div>";
    }
}

if ($cat == 'regular'){
    $query = " select * from shirts where category_2 = '$cat'";
    $result = mysqli_query($con, $query);
    while ($row = mysqli_fetch_array($result))
    {
        $html .= "<div class='des-result'>" . $row['code'] ."</div>";
    }
}

$json[] = array(
    'html' => $html,
    'text' => $text
);

header('Content-Type: application/json');

echo json_encode($json);

?>

jQuery的:

$("body").on("click",".reg", function (){
    $(".des-result").remove();
    $(".reg-result").remove();
    db_name = "shirts";
    category = "regular";
    var data = {

           cat : category
    };
    $.ajax ({
            type:"POST",
            url:"data.php",
            dataType: "json",
            data: data,
            success: function(res) {

                                    $("#result").append(res.html);
                                   console.log(res.text);

                                   },
            error: function(xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
      }
    });

当我点击div

时,下面是控制台上的输出(使用firebug)
 [Object { html="<div class='des-result'>...es-result'>pk-004</div>", text="this is from php server"}]

我以为我能够像这样访问文本和html变量。 res.html和res.text但是如果我控制台登录它会显示未定义。

请指导我在这里错了什么

1 个答案:

答案 0 :(得分:1)

由于您返回数组的方式,正确的结果将是res.0.html,因为您将其作为多维数组。

$json[] = array(
    'html' => $html,
    'text' => $text
);

应改为:

$json = array(
    'html' => $html,
    'text' => $text
);

然后res.html将返回&#34; html&#34;只要json是返回的......