javascript ajax如何解决跨域问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26752069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:26:29  来源:igfitidea点击:

how to solve cross domain in ajax

javascriptjqueryajax

提问by ???

I want to solve my AJAX cross domain problem. This is the error message I receive in Chrome:

我想解决我的 AJAX 跨域问题。这是我在 Chrome 中收到的错误消息:

XMLHttpRequest cannot load http://'myaddress'/TEST/user/login/testuserid . Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers.

XMLHttpRequest 无法加载 http://'myaddress'/TEST/user/login/testuserid 。Access-Control-Allow-Headers 不允许请求头字段 Access-Control-Allow-Origin。

this is my source code

这是我的源代码

$.ajax({
    crossDomain : true,
    dataType : "json",
    url: fullUrl,
    method: method,
    headers:headers,
    data: body,
    success: function(data, state, res){
        if (data == null)
            data = '';

        console.log( '[[[[[[[[SUCCESS!!]]]]]]]   url: ' + url + ',   state:' + state + ',   data : ' + JSON.stringify( data ) );
        callback(data, state, res);
    },
    error: function(data, state){
        if ( data == null )
            data = '';

        console.log( '[[[[[[[[[ERROR!!]]]]]]]]]   url: ' + url + ', s  tate:' + state + ',   data : ' + JSON.stringify( data ) );
        callback(data, state, null);
    }
});

Servlet code for cross Domain

跨域的Servlet代码

httpRes.setHeader("Access-Control-Allow-Origin", "*");
httpRes.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
httpRes.setHeader("Access-Control-Allow-Headers", "*"); 

采纳答案by Apul Gupta

You need to use JSONPto make CROSS DOMAIN Requests.

您需要使用JSONP来制作CROSS DOMAIN Requests.

Please read:

请阅读:

Loading cross domain endpoint with jQuery AJAX

使用 jQuery AJAX 加载跨域端点

Make cross-domain ajax JSONP request with jQuery

使用 jQuery 进行跨域 ajax JSONP 请求