0

我正在尝试集成一个使用 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.

任何建议将不胜感激。

谢谢!

4

1 回答 1

2

如果您用于构造标头的所有内容都是同步的,则只需beforeSend在 ajax 选项中传递一个函数。IE:

    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

于 2014-05-24T11:06:48.037 回答