Ajax中的URL有绝对路径和相对路径之分
项目部署路径为:http://jsy-005:8080/XY_Plan/
页面的请求地址为:http://jsy-005:8080/XY_Plan/
注:jsy-005的IP地址为:192.168.0.105
1.如果Ajax中URL写成如下的格式
$.ajax({
url:"/XY_Plan/LoginServlet",
data:user,
type:"post",
dataType:"json",
success:function(json){
alert("111")
},
error:function(err){
alert(err.status)
}
});
那么,最后的请求路径为http://jsy-005:8080/XY_Plan/LoginServlet
这是因为url中以“/”开头,意思是直接找到当前页面的url路径“http://jsy-005:8080”然后拼接上“/XY_Plan/LoginServlet”;
2.如果Ajax中URL写成如下的格式
$.ajax({
url:"XY_Plan/LoginServlet",
data:user,
type:"post",
dataType:"json",
success:function(json){
alert("111")
},
error:function(err){
alert(err.status)
}
});
那么,最后的请求路径为“http://jsy-005:8080/XY_Plan/XY_Plan/LoginServlet”
这里url中没有以“/”开头,那么会找到当前页面的url地址“http://jsy-005:8080/XY_Plan”再拼接上“/XY_Plan/LoginServlet”,这样就会导致404错误;
3.如果Ajax中URL写成如下的格式
$.ajax({
url:"http://192.168.0.105:8080/XY_Plan/LoginServlet",
data:user,
type:"post",
dataType:"json",
success:function(json){
alert("111")
},
error:function(err){
alert(err.status)
}
});
这种写法最后的请求路径就为ajax中url路径“http://192.168.0.105:8080/XY_Plan/LoginServlet”,
但如果按上面的写法会报异常:
XMLHttpRequest cannot load http://jsy-005:8080/XY_Plan/LoginServlet. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://192.168.0.105:8080' is therefore not allowed access.
这是由于Ajax的跨域导致的,应将ajax的url改为和页面地址栏中的url域名改为一致即可“http://jsy-005:8080/XY_Plan/LoginServlet”,或者将地址栏的url改为“http://192.168.0.105:8080/XY_Plan/”