卷曲请求到ajax

时间:2014-12-12 10:01:40

标签: jquery ajax curl

尝试使用Zendesk API

curl https://{subdomain}.zendesk.com/api/v2/tickets.json \
  -d '{"ticket":{"subject":"My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \
  -H "Content-Type: application/json" -v -u {email_address}:{password} -X POST

当我将其转换为ajax时,工作正常:

var http = "https://SSS.zendesk.com/api/v2/tickets.json";
var data = {"ticket":{"subject":"My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}};


$.ajax({
    url: http,
    beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa("user:pass")); 
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    data: data,
    success: function (data) {
      console.log(JSON.stringify(data));
    },
    error: function(){
      console.log("Cannot get data");
    }
});

我收到错误:

XMLHttpRequest cannot load https://quran.zendesk.com/api/v2/tickets.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://null.jsbin.com' is therefore not allowed access. The response had HTTP status code 422.

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你正在对Same Origin Policy犯规。

您不能将jQuery中的AJAX请求发送到第三方域,除非使用JSONP或CORS(支持它们 - 请查看其文档以获取信息)。

如果您尝试从中检索数据的URL不支持您需要通过本地服务器发出请求的URL,并通过JS检索响应。