因为一些javascript hoisting,变量显示为undefined

时间:2014-06-30 10:01:20

标签: javascript html json hoisting

编辑:好的,我遇到了问题。 ajax成功函数内无法访问#t01 ID,因此无法显示任何内容。它被称为javascript hoisting。但我没有找到解决这个问题的方法。当我将document.getElementById('t01')。innerHTML = content放在ajax语句之外时,我会显示 undefined

我无法从php返回json以显示在我的html中。我不确定,我哪里出错了。

的index.html

 <head>
    <title>Device Properties Example</title>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>

    <script type="text/javascript" charset="utf-8">
     document.addEventListener("deviceready", onDeviceReady, false);
     function onDeviceReady() {
     navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }
    function onSuccess(position) {
    var lat,lon,content;
    var element = document.getElementById('geolocation');

        element.innerHTML = 'Latitude: '           + position.coords.latitude + '<br />' +
                            'Longitude: '          + position.coords.longitude  + '<br />' +
                            'Altitude: '           + position.coords.altitude              + '<br />' +
                            'Accuracy: '           + position.coords.accuracy              + '<br />' +
                            'Altitude Accuracy: '  + position.coords.altitudeAccuracy      + '<br />' +
                            'Heading: '            + position.coords.heading               + '<br />' +
                            'Speed: '              + position.coords.speed                 + '<br />' +
                            'Timestamp: '          + position.timestamp                    + '<br />';
    lat= position.coords.latitude;
    lon= position.coords.longitude;
    $(document).ready(function(){
    $.ajax({
    type: 'GET',
    url: "http://geolocation.webatu.com/Radius.php", 
    data:{lat:lat , lon:lon},
    dataType: 'jsonp',
    success: function(response){
    content = "<ul>";
    var parsed = JSON.parse(response);
    for(var i in parsed){
    content += "<li>" + parsed[i].ClassName+" "+ parsed[i].City+"</li>";
    document.getElementById('t01').innerHTML = content;
    }
}
});
});

}
 function onError(error) {
 alert('code: '    + error.code    + '\n' +
       'message: ' + error.message + '\n');
 }
    </script>
    </head>
    <body>
    <p id="geolocation">Finding geolocation...</p>
    <div id="t01"> </div>   </body>

PHP代码

$con=mysqli_connect($mysql_host,$mysql_user,$mysql_password,$mysql_database);
    $lat = $_GET['lat'];
    $lon = $_GET['lon'];
$var= array();
$sql = mysqli_query($con,"//all the query goes here//") or die('Error: ' . mysqli_error($con));
while($row = mysqli_fetch_array($sql))
        {
    $var[]=$row;
    }
echo '{"college":'.json_encode($var).'}';
mysqli_close($con);

JSON响应

'[{"ID":"1","ClassName":"somaiya","City":"mumbai","latitude":"19.073507000000","longitude":"72.899545000000","distance":"1.04906981264925"}]'

我从mysql获取数据到php,从php开始编码为json并发送到html,但它没有以html显示。

4 个答案:

答案 0 :(得分:1)

首先,函数 json_encode 需要PHP&gt; = 5.2

你的PHP

$sql = mysqli_query($con,"//all the query goes here//");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
   $rows[] = $r;
}
return json_encode($rows);

你的AJAX

$.ajax({
   type: "POST",                
   url: "http://geolocation.webatu.com/Radius.php",
   data:{lat:lat , lon:lon},
   success: function(response) {
        var objData = jQuery.parseJSON(response);
        $('#t01').html(objData );
   }

只需在成功中使用jquery.parseJSON即可。这将给你[对象对象]。你必须使用objData.ID或你想要的东西。我不确定这会完全奏效。根据需要修改代码。

答案 1 :(得分:0)

只需删除此内容......

echo '{"college":'.json_encode($var).'}';

并将其替换为

 return json_encode($var);

要么这样做......要么将你的ajax成功改为这样......

  success: function(response)
    { 
      ver dat = response.college;
    $('#t01').html(dat.ID);

    }

答案 2 :(得分:0)

你必须设置Content-Type标题:

<?php
    $var = /** whatever you're serializing **/;
    header('Content-Type: application/json');
    echo json_encode($var);
?>

您可以通过在浏览器上直接键入脚本的URL来验证编码的json字符串 然后,您可以通过JavaScript /

将数据作为对象获取

答案 3 :(得分:0)

在index.html中,您有success: function(response)var college = data.college。将其更改为var college = response.college