$ .ajax ответ пуст - PullRequest
       4

$ .ajax ответ пуст

0 голосов
/ 28 декабря 2011

Я видел другие связанные вопросы, но не смог найти точного соответствия моей проблеме на SO.Попытка вернуть JSON с worldweatheronline.com с помощью $ .ajax и постоянно получать пустой ответ.В Fiddler, однако, я вижу правильный ответ каждый раз, только в браузере, он кажется пустым (ищется с помощью Firebug и операторов alert).Используя метод .ajax, я хочу проанализировать JSON при наличии ответа.

Ниже приведен фрагмент кода, необработанный запрос и необработанный ответ.

            var jsonxhr = $.ajax({
            url: 'http://free.worldweatheronline.com/feed/weather.ashx?q=55122&format=json&num_of_days=5&key=<somekey>',
            type: 'GET',
            dataType: 'jsonp',
            success: function (json) {
                alert('request success');
            },
            error: function (xhr, status) {
                alert('request error');
            },
            complete: function (xhr, status) {
                //alert('request complete');
                try {
                    var parsedJson = $.parseJSON(jsonxhr.responseText);
                    //alert('success parsing');
                    alert('test' + jsonxhr.responseText + 'test');
                    alert('headers ' + jsonxhr.getAllResponseHeaders());
                    //alert(parsedJson.data.weather.tempMaxF.toString());
                }
                catch (e) {
                    alert("error parsing");
                }
            }
        });

Необработанный запрос

GET http://free.worldweatheronline.com/feed/weather.ashx?q=55122&format=json&num_of_days=5&key=somekey HTTP / 1.1 Accept: / Accept-Language: en-US Accept-Encoding: gzip, deflate User-Agent: Mozilla / 4.0 (совместимо;MSIE 7.0; Windows NT 6.1; Trident / 5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Медиа-центр ПК 6.0; .NET4.0C; .NET4.0E; ПланшетПК 2.0) Соединение: Keep-Alive Хост: free.worldweatheronline.com

Необработанный ответ

HTTP / 1.1 200 OK Cache-Control: private Content-Type: application/ JSON;charset = utf-8 Сервер: Microsoft-IIS / 7.5 X-AspNet-версия: 2.0.50727 X-Powered-By: ASP.NET Дата: среда, 28 декабря 2011 04:20:46 GMT Длина контента: 2712

{"data": {"current_condition": [{"cloudcover": "100", "влажность": "50", "Время наблюдения": "03:50 AM", "осадковMM": "0.0", "pressure": "1017", "temp_C": "-3", "temp_F": "26", "visibility": "16", "weatherCode": "122", "weatherDesc": [{"value":" Overcast "}]," weatherIconUrl ": [{" value ":" http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"}], "winddir16Point": "N", "winddirDegree": "10", "windspeedKmph": "11", "windspeedMiles ":" 7 "}]," request ": [{" query ":" 55122 "," type ":" Zipcode "}]," weather ": [{" date ":" 2011-12-27 ", "degMM": "0.0", "tempMaxC": "2", "tempMaxF": "35", "tempMinC": "-4", "tempMinF": "24", "weatherCode": "113","weatherDesc": [{"value": "Sunny"}], "weatherIconUrl": [{"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"}]," winddir16Point ":" NNW "," winddirDegree ":" 343 ","winddirection ":" NNW "," windspeedKmph ":" 28 "," windspeedMiles ":" 18 "}, {" date ":" 2011-12-28 "," осадковMM ":" 0.0 "," tempMaxC ":" 2 "," tempMaxF ":" 36 "," tempMinC ":" -6 "," tempMinF ":" 22 "," weatherCode ":" 113 "," weatherDesc": [{" value ":" Sunny "}]," weatherIconUrl ": [{" value ":" http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"}], "winddir16Point": "SW", "winddirDegree": "220", "winddirection": "SW", "windspeedKmph": "17", "windspeedMiles": "11"}, {"date": "2011-12-29", "deposMM": "0.3", "tempMaxC": "4", "tempMaxF": "39", "tempMinC": "-1", "tempMinF": "30", "weatherCode": "116", "weatherDesc": [{"value": "Небольшая облачность"}], "weatherIconUrl": [{"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"}]," winddir16Point ":" WSW "," winddirDegree ":" 257 "," winddirection ":" WSW "," windspeedKmph ":" 20 ","windspeedMiles": "13"}, {"date": "2011-12-30", "deposMM": "0.3", "tempMaxC": "1", "tempMaxF": "35", "tempMinC":"-1", "tempMinF": "30", "weatherCode": "119", "weatherDesc": [{"value": "Cloudy"}], "weatherIconUrl": [{"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png"}], "winddir16Point": "SW", "winddirDegree": "228", "winddirection": "SW", "windspeedKmph": "18", "windspeedMiles": "11"}, {"date":" 2011-12-31 "," degMM ":" 0,7 "," tempMaxC ":" 4 "," tempMaxF ":" 39 "," tempMinC ":" 0 "," tempMinF ":" 32 ","weatherCode": "122", "weatherDesc": [{"value": "Overcast"}], "weatherIconUrl": [{"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"}]," winddir16Point ":" W ","winddirDegree ":" 268 "," winddirection ":" W "," windspeedKmph ":" 21 "," windspeedMiles ":" 13 "}]}}

1 Ответ

2 голосов
/ 28 декабря 2011

Я считаю, что проблема в том, что jsonp на самом деле не AJAX.Из-за этого объект xhr не имеет всего, что вы могли бы ожидать увидеть в реальном вызове AJAX.Вместо этого вы должны использовать данные, которые передаются обратному вызову success.

...