Access-Control-Allow-Origin不允许使用origin http:// localhost:8080

时间:2014-04-09 07:46:56

标签: javascript jquery ajax

您好已经有很多与此问题相关的线程了。 但我仍然陷入困境。当我尝试访问此REST api时,我无法得到响应。我无法控制服务器端响应头,因为它的公共API。可以帮助解决此问题。

以下是我的代码

$(document).ready(function() {
    $("#medication").autocomplete({
        select : function(request, response) {
        //$(this).value(response.item.value);
        getMedicationIdByName(response.item.value);
    },
    search  : function(){$(this).addClass('working');},
    open    : function(){$(this).removeClass('working');},

    source : function(request, response) {
        $.ajax({

            headers : {
                        Accept : "application/json; charset=utf-8",
                        "Content-Type" : "application/json; charset=utf-8"
            },
            type : "GET",
            url : "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
            data : "name="+ request.term,
            crossDomain: 'true',
            dataFil ter : function(data) {
                return data;
            },

            success : function(data) {
                try {
                        //alert("success!!"+JSON.stringify(data));

                        data = data.suggestionGroup.suggestionList["suggestion"]+ "";
                        data = data.split(",");

                        response($.map(data,function(item) {
                            //alert("success!!"+JSON.stringify(item))
                            return {
                                    value : item
                            };
                        }));
                } catch (e) {
                    alert(e);
                }

            },
            error : function() {
                alert('Cannot connect to REST API!!!');
            }
        });
    },
    minLength : 4
    });
});

1 个答案:

答案 0 :(得分:1)

您需要在ajax请求中将dataType设置为jsonp

type: "GET",
headers: { 
    Accept : "application/json; charset=utf-8",
    "Content-Type": "application/json; charset=utf-8"
},
url: "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data: { name: "bard"},
dataType: "jsonp",
crossdomain: true,