显示来自ajax api调用的jsonp数据

时间:2017-01-12 22:05:27

标签: javascript jquery

运行此代码时,检查时出现语法错误。我想在“输出”div中显示结果,但似乎存在翻译问题。我必须使用jsonp,因为我正在访问一个我无法控制的服务器。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"     rel="javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" rel="jquery">    </script>
</head>

<body style="margin: 0px; padding: 0px;">

<div id="fullscreen">
<div id="output">

</div>

</div>

</body>


<script>
$.ajax({
type: 'GET',
url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/players?limit=1&offset=0&sort=name",
dataType: "jsonp",
jsonpCallback: 'callback',
//data: {format: "jsonp"},
//data: JSON.stringify,
 success: function( response ) {
    console.log( response ); // server response
   {
    var id = data[0];       
    var vname = data[1];           

    $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
  } 
}
});
</script>

跨域:

var proxyJsonp="https://script.google.com/macros/s/AKfycbwmqG55tt2d2FcT_WQ3WjCSKmtyFpkOcdprSITn45-4UgVJnzp9/exec";
jQuery.ajaxOrig=jQuery.ajax;jQuery.ajax=function(a,b){function d(a){a=encodeURI(a).replace(/&/g,"%26");return proxyJsonp+"?url="+a+"&callback=?"}var c="object"===typeof a?a:b||{};c.url=c.url||("string"===typeof a?a:"");var c=jQuery.ajaxSetup({},c),e=function(a,c){var b=document.createElement("a");b.href=a;return c.crossOrigin&&"http"==a.substr(0,4).toLowerCase()&&"localhost"!=b.hostname&&"127.0.0.1"!=b.hostname&&b.hostname!=window.location.hostname}(c.url,c);c.proxy&&0<c.proxy.length&&(proxyJsonp=c.proxy,"object"===typeof a?
a.crossDomain=!0:"object"===typeof b&&(b.crossDomain=!0));e&&("object"===typeof a?a.url&&(a.url=d(a.url),a.charset&&(a.url+="&charset="+a.charset),a.dataType="json"):"string"===typeof a&&"object"===typeof b&&(a=d(a),b.charset&&(a+="&charset="+b.charset),b.dataType="json"));return jQuery.ajaxOrig.apply(this,arguments)};jQuery.ajax.prototype=new jQuery.ajaxOrig;jQuery.ajax.prototype.constructor=jQuery.ajax;

1 个答案:

答案 0 :(得分:0)

通过该链接的外观,服务器返回JSON,而不是JSONP。如果API支持它,您应该使用CORS代替。

示例:

$.ajax({
    type: 'GET',
    url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/players?limit=1&offset=0&sort=name",
    dataType: "json",
    crossDomain: true,
    success: function( response ) {
            console.log( response ); // server response
            var id = response[0];       
            var vname = response[1];
            $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
    }
});