2015-12-15 8 views
-2

Пожалуйста, помогите мне. Я новичок в вызове ajax из json, я мог бы получить данные от json, пожалуйста, посмотрите из ниже кода.JQuery Ajax call from json get error

Можно ли позвонить с локального сервера, как его работали,

Пожалуйста, дайте Битый ясную картину

В хромированной ошибке консоли:

XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/weather?q=%2C. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8012' is therefore not allowed access. The response had HTTP status code 401. 

код:

<!DOCTYPE html> 
    <html> 
    <script src="http://localhost:8012/js/jquery.min.js"></script> 
    <body> 
    <div> city : <input type="text" id="txtCity"></div><br/> 
    <div> Country : <input type="text" id="txtCountry"></div><br/> 
    <input type="button" value="Get weather" id="getWeather"> 
    <div id="#resultDiv"></div> 
    <script> 
     $(document).ready(function() { 
     $("#getWeather").click(function() { 

      var requestData = $("#txtCity").val() + ',' + $("#txtCountry").val(); 
      var resultElement = $("#resultDiv"); 

       $.ajax({ 
         url: 'http://api.openweathermap.org/data/2.5/weather', 

         method: 'get', 
         data: { 
          q: requestData 
         }, 
         dataType: 'json', 
         success: function(data) { 
          resultElement.html('weather: ' + data.weather[0].main + '<br/>' + 
           'Description: ' + data.weather[0].description); 
        } 

       }); 

    //alert("test"); 

     }); 

    }); 
    </script> 
    </body> 
    </html> 
+2

столько раз задал этот вопрос. проблема cors. –

+2

http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working check –

+0

использовать jsonp вместо json и разрешать cors. –

ответ

-1

Вам нужно для установки заголовка «Access-Control-Allow-Origin» в вашем запросе.

Я видел, что вы используете dataType: 'json', попробуйте dataType: 'jsonp' и добавьте crossDomain: true внутри вашего $ .ajax может быть достаточно.

Если вы хотите установить заголовок запроса, вы можете попробовать что-то вроде

$.ajax({ 
    url: 'http://api.openweathermap.org/data/2.5/weather', 
    beforeSend: function(xhr) { 
     xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); 
    }, 
    method: 'get', 
    data: { q: requestData}, 
    dataType: 'json', 
    success: function(data) { 
    resultElement.html('weather: ' + data.weather[0].main + '<br/>' + 'Description: ' + data.weather[0].description);} 
}); 
+0

Привет AndreaScn, что для справки, когда я запускаю консольный метод: получение ошибки «Uncaught SyntaxError: Неожиданный идентификатор "по методу: get –

+0

Моя ошибка, я забыл запятую после функции' beforeSend'. Я только что исправил код :) – AndreaScn

+0

Вы не можете установить CORS на клиентов ... Это победит цель ... – epascarello

0

Убедитесь, что сервер вы отправляете запрос может принять ваш запрос. Это сводка how CORS principle works. Я прочитал на openweathermap.org/appid, что вам нужен ключ API, чтобы сделать правильный запрос. Вот пример вызова API: http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=1111111111. Я предлагаю вам прочитать на своем сайте, как получить токен API и сделать правильный запрос.