我正在调用2Checkout提供的rest API。这是我的代码
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json",
accepts: {json:"application/json"},
url: "https://api.2checkout.com/rest/5.0/subscriptions/9C77B952C2/",
success: function(data){
},
error: function(){
}
});
执行此代码时,出现错误:net::ERR_ABORTED 415
当我尝试在新标签页中打开URL时,会得到:
{"error_code":"INVALID_CONTENT_TYPE","message":"The current resource can not be served as [text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, image/apng, */*;q=0.8] content-types"}
因此,基于这一点,我需要指定服务器要接受的正确内容类型,这就是我添加的原因:
accepts: {json:"application/json"},
2Checkout支持告诉我"when using REST API make sure that http header also contains “Accept: application/json”. This is mandatory for the call to work and for retrieving info."
但是他们唯一的例子是原始javascript,而不是jQuery。 javascript示例如下:
var request = new XMLHttpRequest();
request.open('GET', 'https://api.2checkout.com/rest/5.0/subscriptions/{SubscriptionReference}/');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
request.send();
因此,我想尽可能在jQuery中进行此操作,我觉得这应该不难,但我仍然会收到错误消息。
不幸的是,jQuery文档不是很具体,只是给出了一个自定义类型的示例,我认为这不是。它还说,“ accepts”的默认值取决于数据类型,在我的情况下为jsonp,因此我假设它会自动接受application / json,但不会。
这有什么窍门?