我正在尝试集成一个自动完成字段,该字段使用REST获取其信息。我正在使用Typeahead / Bloodhound。我按照文档中的示例进行了跟踪,但我无法在任何地方找到如何设置标头,以便使其正常工作。例如,这是代码:
var countries = new Bloodhound({
datumTokenizer: function(countries) {
return Bloodhound.tokenizers.whitespace(countries);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
,
prefetch: {
url: "http://localhost/api-1.1/search/country/key/%QUERY",
filter: function(response) {
return response.countries;
}
}
});
// initialize the bloodhound suggestion engine
countries.initialize();
// instantiate the typeahead UI
$('.typeahead').typeahead(
{ hint: true,
highlight: true,
minLength: 1
},
{
name: 'country_label',
displayKey: function(countries) {
return countries.country.country_name;
},
source: countries.ttAdapter()
});
这是我在控制台日志中从服务器获得的响应:
XMLHttpRequest cannot load http://localhost/api-1.1/search/country/key/%QUERY. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
任何建议都会非常感激。
谢谢!
答案 0 :(得分:2)
如果用于构建标题的所有内容都是同步的,则可以在ajax选项中传递beforeSend
函数。即:
prefetch: {
url: "http://localhost/api-1.1/search/country/key/%QUERY",
filter: function(response) {
return response.countries;
},
ajax: {
beforeSend: function(jqXHR, settings) {
var authHeaders;
// pull apart jqXHR, set authHeaders to what it should be
jqXHR.setRequestHeader('Authorization', authHeaders);
}
}
}
只是没有混淆,您正在设置auth标头以获取对API的访问权限,API定义Access-Control-Allow-Origin