0

Ajax 不想$google['cities']在调用时识别我的data.cities.

输出是:12 undefined undefined

如果我删除它,它工作得很好(输出是数据库记录)$google['number']=12,并将数据库数组定义为$google[]=$row.

有任何想法吗?

PHP:

<?php

$con = mysql_connect("localhost","root","");

if(!$con) {

    die("Connection Error: ".mysql_error());

}

mysql_select_db("avtost", $con);

$pasteta = $_POST["white"];

$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");

mysql_close($con);

$google=array();

while ($row=mysql_fetch_array($places)) {
    $google["cities"]=$row;
}

$google['number']=12;

if (mysql_num_rows($places)>0) {

    echo json_encode($google);
} else { echo 'Ni rezultatov';}



?>

查询:

<script type="text/javascript">

$(document).ready(function(){

  $('#submit').click(function(){

    var white = $('#white').val();

    $.ajax({

    type:"POST",
    url:"page.php",
    dataType:'json',
    data:{white:white},
    success: function(data){

        var result='';
        $.each(data.cities, function(i,e) {
        result += '<div>'+e.sDo+'</div>';
        });
        $("#res").append(data.number);
        $("#res").append(result);

    }


    });


  });  

});

</script>
4

3 回答 3

3

每次cities在. _ 您可以使用:$google$places

while ($row=mysql_fetch_array($places)) {
    $google[]=$row;
}

$google[]=12;

然后如果要获取数字键,只需获取数组的最后一个值值,或者只是将数字作为单独的变量传递$number

于 2012-08-01T23:56:38.610 回答
3

一些技巧:

1)您应该使用准备好的语句来保护您的代码(mysqli准备好的)。这会给你类似的东西:

// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
    $google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...

2) 改进你的变量、表和列名。他们有点混乱。

3) 您应该返回 JSON,而不是返回 'Ni rezultatov'。例如,{"status":"FAILED"},随后返回{"status":"OK", ... }成功的请求。

于 2012-08-02T00:16:07.970 回答
1

我自己解决了:

PHP:

while($row=mysql_fetch_array($places)){

$google['cities'][]=$row;

}

$google['number']=12;

echo json_encode($google);
于 2012-08-02T00:12:33.273 回答