最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Parsing JSON Ajax response - Stack Overflow

programmeradmin1浏览0评论

I'm running into trouble parsing a JSON response. I've done this lots of times but this is not working for a reason I cannot discern. Here is what I'm doing:

Before anyone suggests it - due to some requirements of the project I am working on I have to use the server side Google Geocoding web service, I can't do it all client side.

I'm using PHP for the server side portion. I'm using AJAX(via jQuery) to send the location to the server, getting the response and returning it encoded as JSON. Here is the server side code:

<?php
if(!empty($_POST['theLocation']))
{
    $loc = urlencode($_POST['theLocation']);

    $response = file_get_contents("=$loc,+CA&sensor=false");
    echo  json_encode($response);
}
?>

Here is the client side call, where theLocation is a location name:

 var postdata = "theLocation=" + encodeURIComponent(theLocation);
$.ajax( {
    type : "POST",
    url : "GeoEncode.php",
    data :postdata ,
    dataType : "JSON",
    success : function(data) {
        data = $.parseJSON(data);

        lat = data.results[0].geometry.location.lat;
        lng = data.results[0].geometry.location.lng;

    },
    error: function (request, status, error) {
        log("Error: getLatLong Status - " + status + " ErrorText - " + error);
    }
});

When I try to access data.results[0] I get the error Uncaught TypeError: Cannot read property '0' of undefined. This obviously means that there is no results property. However if I do a console.log(data) This is what I get:

{
    "results": [
        {
            "address_ponents": [
                {
                    "long_name": "Halifax",
                    "short_name": "Halifax",
                    "types": [
                        "locality",
                        "political"
                    ]
                },
                {
                    "long_name": "Halifax",
                    "short_name": "Halifax",
                    "types": [
                        "administrative_area_level_3",
                        "political"
                    ]
                },
                {
                    "long_name": "Halifax Regional Municipality",
                    "short_name": "Halifax Regional Municipality",
                    "types": [
                        "administrative_area_level_2",
                        "political"
                    ]
                },
                {
                    "long_name": "Nova Scotia",
                    "short_name": "NS",
                    "types": [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name": "Canada",
                    "short_name": "CA",
                    "types": [
                        "country",
                        "political"
                    ]
                }
            ],
            "formatted_address": "Halifax, NS, Canada",
            "geometry": {
                "bounds": {
                    "northeast": {
                        "lat": 44.7035312,
                        "lng": -63.55963089999999
                    },
                    "southwest": {
                        "lat": 44.5949302,
                        "lng": -63.68627009999999
                    }
                },
                "location": {
                    "lat": 44.6488625,
                    "lng": -63.5753196
                },
                "location_type": "APPROXIMATE",
                "viewport": {
                    "northeast": {
                        "lat": 44.7035312,
                        "lng": -63.55963089999999
                    },
                    "southwest": {
                        "lat": 44.5949302,
                        "lng": -63.68627009999999
                    }
                }
            },
            "types": [
                "locality",
                "political"
            ]
        }
    ],
    "status": "OK"
}

This is valid JSON, there is clearly a results property. I don't know why I am having trouble with this, I must be missing something but through my debugging I have yet to find out what. If anyone could offer any suggestions it would be very much appreciated. Thanks!

I'm running into trouble parsing a JSON response. I've done this lots of times but this is not working for a reason I cannot discern. Here is what I'm doing:

Before anyone suggests it - due to some requirements of the project I am working on I have to use the server side Google Geocoding web service, I can't do it all client side.

I'm using PHP for the server side portion. I'm using AJAX(via jQuery) to send the location to the server, getting the response and returning it encoded as JSON. Here is the server side code:

<?php
if(!empty($_POST['theLocation']))
{
    $loc = urlencode($_POST['theLocation']);

    $response = file_get_contents("http://maps.googleapis./maps/api/geocode/json?address=$loc,+CA&sensor=false");
    echo  json_encode($response);
}
?>

Here is the client side call, where theLocation is a location name:

 var postdata = "theLocation=" + encodeURIComponent(theLocation);
$.ajax( {
    type : "POST",
    url : "GeoEncode.php",
    data :postdata ,
    dataType : "JSON",
    success : function(data) {
        data = $.parseJSON(data);

        lat = data.results[0].geometry.location.lat;
        lng = data.results[0].geometry.location.lng;

    },
    error: function (request, status, error) {
        log("Error: getLatLong Status - " + status + " ErrorText - " + error);
    }
});

When I try to access data.results[0] I get the error Uncaught TypeError: Cannot read property '0' of undefined. This obviously means that there is no results property. However if I do a console.log(data) This is what I get:

{
    "results": [
        {
            "address_ponents": [
                {
                    "long_name": "Halifax",
                    "short_name": "Halifax",
                    "types": [
                        "locality",
                        "political"
                    ]
                },
                {
                    "long_name": "Halifax",
                    "short_name": "Halifax",
                    "types": [
                        "administrative_area_level_3",
                        "political"
                    ]
                },
                {
                    "long_name": "Halifax Regional Municipality",
                    "short_name": "Halifax Regional Municipality",
                    "types": [
                        "administrative_area_level_2",
                        "political"
                    ]
                },
                {
                    "long_name": "Nova Scotia",
                    "short_name": "NS",
                    "types": [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name": "Canada",
                    "short_name": "CA",
                    "types": [
                        "country",
                        "political"
                    ]
                }
            ],
            "formatted_address": "Halifax, NS, Canada",
            "geometry": {
                "bounds": {
                    "northeast": {
                        "lat": 44.7035312,
                        "lng": -63.55963089999999
                    },
                    "southwest": {
                        "lat": 44.5949302,
                        "lng": -63.68627009999999
                    }
                },
                "location": {
                    "lat": 44.6488625,
                    "lng": -63.5753196
                },
                "location_type": "APPROXIMATE",
                "viewport": {
                    "northeast": {
                        "lat": 44.7035312,
                        "lng": -63.55963089999999
                    },
                    "southwest": {
                        "lat": 44.5949302,
                        "lng": -63.68627009999999
                    }
                }
            },
            "types": [
                "locality",
                "political"
            ]
        }
    ],
    "status": "OK"
}

This is valid JSON, there is clearly a results property. I don't know why I am having trouble with this, I must be missing something but through my debugging I have yet to find out what. If anyone could offer any suggestions it would be very much appreciated. Thanks!

Share Improve this question asked Feb 1, 2013 at 19:56 TheMethodTheMethod 3,00011 gold badges44 silver badges76 bronze badges 2
  • @Pete Why would that help? The content being sent is in the right format already – Ian Commented Feb 1, 2013 at 20:00
  • 3 The google api is already returning a JSON string, so you don't need to json_encode it. – Supericy Commented Feb 1, 2013 at 20:01
Add a ment  | 

1 Answer 1

Reset to default 9

You are settingdataType: 'json'. This means that jQuery will parse the result as JSON for you.

Lose the data = $.parseJSON(data); line, then it should work.

Also, as @SLaks pointed out: in your PHP, $response is already in JSON format. No need to json_encode it. Just echo $response.

发布评论

评论列表(0)

  1. 暂无评论