【发布时间】:2017-03-10 11:30:08
【问题描述】:
我对 REST 服务器上的 ajax GET 请求有疑问。我做了一些测试,我会在这里发布。
在 REST 服务器中我有两种方法:
- 1) resource_new_get(返回json数据,不需要自定义头部)
- 2) resource_api_new_get(返回与第一个相同的 json 数据,但需要 Api-Key 自定义标头)
这是在服务器上执行 ajax 请求的 javascript 代码(在 resource_new_get 方法上):
app.updateResources = function(data)
{
if(data == null)
{
$.ajax(
{
url: 'http://<remotehost>/api/events/resource_new?id_event=<ID>',
dataType: 'json',
success: function(d)
{
console.log(d);
},
error: function(error)
{
console.log('error ' + JSON.stringify(error));
}
});
}
else
{
...
}
};
在这种情况下,ajax 请求运行良好,我能够从服务器获取 json 响应。
但是当我向 resource_api_new 执行请求时,添加自定义标头如下:
app.updateResources = function(data)
{
if(data == null)
{
$.ajax(
{
url: 'http://<remotehost>/api/events/resource_api_new?id_event=<ID>',
dataType: 'json',
headers: {'Api-Key': '<my_token>'},
success: function(d)
{
console.log(d);
},
error: function(error)
{
console.log('error ' + JSON.stringify(error));
}
});
}
else
{
...
}
};
这需要标头中的“Api-Key”键标识的令牌来返回 json 响应,错误函数触发并返回:
XMLHttpRequest cannot load http://<remotehost>/v2/index.php/api/events/resource_api_new?id_event=<ID>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://<myhost>' is therefore not allowed access. The response had HTTP status code 404.
当我在包含 REST 服务器的 php 文件顶部添加以下行:
header('Access-Control-Allow-Origin: *');
响应返回“简单”的HTTP状态码404,如下:
XMLHttpRequest cannot load http://api.gtmasterclub.it/v2/index.php/api/eventi/relatori_api_new?id_evento=159. Response for preflight has invalid HTTP status code 404
【问题讨论】:
标签: javascript php jquery json ajax