考虑此标题信息:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic TWluZVN0YXI6TWluZVN0YXI=
Cache-Control:max-age=0
Connection:keep-alive
Host:*
此标题信息适用于网址。 我试图从这个网址获取json值。单独访问此URL时会弹出用户名和密码。
TRY1:
$.ajax({
type:'GET',
url: 'http://'+domainName+':9898/*/*',
dataType:"json",
username: '*',
password: '*',
async: false
}).responseText;
TRY2
$.ajax({
type:'GET',
url: 'http://'+domainName+':9898/jolokia/*/*',
dataType:"json",
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa('*' + ":" + '*'));
},
async: false
}).responseText;
TRY3:
尝试在tomcat的web.xml中添加它。
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request- Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param- value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但我仍然无法访问该网址,但仍会出现以下错误:
GET http://***.**.**.**:9898/*/* 401 (Unauthorized)
jquery.min.js:5 XMLHttpRequest cannot load http://**.**.**.**:9898/*/*. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:8080 is therefore not allowed access. The response had HTTP status code 401.(index):1 Uncaught SyntaxError: Unexpected token u
我只需要访问url并从该url获取json值。用户名和密码保护URL,我知道。
我现在不知道这可能是一个跨域问题。当我从url中删除身份验证时,此代码正常工作:
$.ajax({
type:'GET',
url: 'http://'+domainName+':9898/*/*',
dataType:"json",
async: false
}).responseText;
但是一旦我验证了代码失败的url,在应用了上述步骤之后,代码就会失败。
答案 0 :(得分:0)
尝试从ajax方法中删除dataType:“json”。也许服务器方法获取json字符串但不使用json content-type
答案 1 :(得分:0)
不需要jsonp。我用它来得到它:
$.ajax({
xhrFields: { withCredentials: true },
type:'GET',
url: 'http://'+domainName+':9898/jolokia/*/*',
dataType:"json",
crossDomain: true,
async: false
}).responseText;
答案 2 :(得分:0)
尝试设置额外的jquery ajax参数:
xhrFields: { withCredentials: true }
这将启用cors功能。