javascript 解析 JSON Ajax 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14654004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:14:35  来源:igfitidea点击:

Parsing JSON Ajax response

phpjavascriptjqueryajaxjson

提问by TheMethod

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:

我在解析 JSON 响应时遇到了麻烦。我已经这样做了很多次,但由于我无法辨别的原因,这不起作用。这是我在做什么:

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。我正在使用 AJAX(通过 jQuery)将位置发送到服务器,获取响应并将其返回编码为 JSON。这是服务器端代码:

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

    $response = file_get_contents("http://maps.googleapis.com/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:

这是客户端调用,其中 theLocation 是位置名称:

 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:

当我尝试访问时data.results[0]出现错误Uncaught TypeError: Cannot read property '0' of undefined。这显然意味着没有 results 属性。但是,如果我这样做,console.log(data)这就是我得到的:

{
    "results": [
        {
            "address_components": [
                {
                    "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!

这是有效的 JSON,显然有一个 results 属性。我不知道为什么我遇到了这个问题,我一定是遗漏了一些东西,但是通过我的调试我还没有找到什么。如果有人可以提供任何建议,将不胜感激。谢谢!

回答by Rocket Hazmat

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

您正在设置dataType: 'json'. 这意味着 jQuery 将为您将结果解析为 JSON。

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

失去data = $.parseJSON(data);线路,然后它应该工作。

Also, as @SLaks pointed out: in your PHP, $responseis alreadyin JSON format. No need to json_encodeit. Just echo $response.

此外,作为@SLaks指出:在你的PHP,$response已经JSON格式。没必要json_encode吧。只是echo $response