来自Ajax-Call的响应无法正常工作 [英] Response from Ajax-Call not working

查看:253
本文介绍了来自Ajax-Call的响应无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

when I execute an ajax call, I get following error:

未捕获的语法错误:意外的令牌:

"Uncaught SyntaxError: Unexpected token :"

我的jquery代码如下所示:

My jquery code looks like this:

$.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) {

    }
});

为什么我不能获得json响应。当在浏览器中直接使用相同的URL时,我得到期望的json响应。
错误?

Why do I not get a json response. When using the same url in my browser directly, I get the expecting json response. What is wrong?

推荐答案

您确实遇到了CORS问题。

You are surely experiencing a CORS issue.

这种方法应该完美工作:

This approach should perfectly work:

$.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.
  }
});

资料来源:使用CORS

这篇关于来自Ajax-Call的响应无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆