使用带有 JSONP 的 AJAX 未捕获的 SyntaxError 和 CORS 错误

Posted

技术标签:

【中文标题】使用带有 JSONP 的 AJAX 未捕获的 SyntaxError 和 CORS 错误【英文标题】:Uncaught SyntaxError and CORS error using AJAX with JSONP 【发布时间】:2016-12-21 14:13:49 【问题描述】:

当我执行 AJAX 调用时,出现以下错误:

Uncaught SyntaxError: Unexpected token :

但是,当我直接在浏览器中访问相同的 URL 时,我得到了预期的 JSON 响应。

我做错了什么,我该如何解决?

下面是我的 jQuery AJAX 请求;

$.ajax(
    type: 'GET',
    url: "http://www.exampleUrl.com",
    crossDomain: true,
    dataType: "jsonp",
    jsonp: "jsonp",
    mimeType: "application/json",
    jsonpCallback: 'callback',
    contentType: "application/json; charset=utf-8",
    beforeSend: function() 
        //
    ,
    success: function (data) 
        alert("success");
    ,
    error: function (result) 
        //      
    
);

【问题讨论】:

【参考方案1】:

您肯定遇到了 CORS 问题。

这种方法应该很有效:

$.ajax(

  // The 'type' property sets the HTTP method.
  // A value of 'PUT' or 'DELETE' will trigger a preflight request.
  type: 'GET',

  // The URL to make the request to.
  url: 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html',

  // The 'contentType' property sets the 'Content-Type' header.
  // The JQuery default for this property is
  // 'application/x-www-form-urlencoded; charset=UTF-8', which does not trigger
  // a preflight. If you set this value to anything other than
  // application/x-www-form-urlencoded, multipart/form-data, or text/plain,
  // you will trigger a preflight request.
  contentType: 'text/plain',

  xhrFields: 
    // The 'xhrFields' property sets additional fields on the XMLHttpRequest.
    // This can be used to set the 'withCredentials' property.
    // Set the value to 'true' if you'd like to pass cookies to the server.
    // If this is enabled, your server must respond with the header
    // 'Access-Control-Allow-Credentials: true'.
    withCredentials: false
  ,

  headers: 
    // Set any custom headers here.
    // If you set any non-simple headers, your server must include these
    // headers in the 'Access-Control-Allow-Headers' response header.
  ,

  success: function() 
    // Here's where you handle a successful response.
  ,

  error: function() 
    // Here's where you handle an error response.
    // Note that if the error was due to a CORS issue,
    // this function will still fire, but there won't be any additional
    // information about the error.
  
);

来源:Using CORS

【讨论】:

感谢您的帖子。现在我收到以下响应错误:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。 这表明 CORS 未在您使用的服务器上正确定义和/或启用。检查enable-CORS 以获取有关如何有效解决它的更多信息。希望您可以访问服务器!

以上是关于使用带有 JSONP 的 AJAX 未捕获的 SyntaxError 和 CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章

jQuery JSONP“未捕获的语法错误:意外的令牌:”

WCF 跨域使用 Jsonp 错误未捕获语法错误:意外令牌:

使用 JSONP 时如何捕获 jQuery $.getJSON(或数据类型设置为“jsonp”的 $.ajax)错误?

获取未捕获的语法错误:意外的令牌:读取 jsonp 响应时

“未捕获的语法错误:意外的令牌:”与 $http.jsonp

JSONP 不适用于 ExtJS 4 - 未捕获的类型错误:无法调用未定义的方法“子字符串”