从URL中提取json的错误

时间:2017-02-26 10:42:22

标签: javascript jquery

我收到错误消息:SyntaxError: Unexpected token ':'. Parse error."

我是否



url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';
function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP(url, function(data){
    console.log(data);
});  

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html><body>
&#13;
&#13;
&#13;

或者如果我这样做:

&#13;
&#13;
url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';

function CallURL() {
  $.ajax({
    url: url,
    type: "GET",
    dataType: "jsonp",
    async: false,
    success: function(msg) {
      console.log(msg);
      JsonpCallback(msg);
    },
    error: function() {
      // ErrorFunction();
      // break ;
    }
  });
}

function JsonpCallback(json) {
  alert(json);
  //document.getElementById('summary').innerHTML = json.result;
}

CallURL();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>

<body>

</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

此网址不返回JSONP,它返回JSON:

{"time":"2017-02-25T12:00:00Z","location":{"latitude":18.75,"longitude":76.75},"data":10.8}

OpeanWeather API仅支持少数几个调用的JSONP,如http://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=c0d8761ca979157a45651a5c7f12a6be,其他调用只支持JSON,XML或HTML(详见https://openweathermap.org/current)。

所以在ajax类型调用中使用 json

url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';

function CallURL() {
  $.ajax({
    url: url,
    type: "GET",
    dataType: "json",
    async: false,
    success: function(msg) {
      console.log(msg);
    },
    error: function() {
      // ErrorFunction();
      // break ;
    }
  });
}

CallURL();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>

<body>

</body>

</html>