我正在尝试使用英国议会 API,但遇到此错误:
XMLHttpRequest cannot load http://findyourmp.parliament.uk/api/search?q=london&f=js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.
我知道这意味着什么,但是没有 JSONP 选项,而且我无法编辑议会的 API。我该如何解决这个问题?我可以通过服务器上允许访问的 PHP 文件路由请求吗?还是不能解决问题?
这是我的代码:
var search_term = $('#input').val();
var url = 'http://findyourmp.parliament.uk/api/search?q=' + search_term + '&f=js';
$.getJSON(url, function(jd) {
$('#div').html('<p>Constituency: ' + jd.constituency_name + '</p>');
});
编辑
最佳答案
是的,使用服务器端“代理”可以解决问题,因为 Access-Control-Allow_Origin 用于客户端调用
简单的 php 代码片段
$search_term = "find";
$url = "http://findyourmp.parliament.uk/api/search?q=".$search_term."&f=js";
return file_get_contents($url);
关于javascript - 没有 'Access-Control-Allow-Origin' header ,但无法访问 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938277/