我正在学习jQuery和REST webservices。下面的代码返回我使用rest jersey创建的rest webservice的HTML响应。
@Path("/hello")
public class HelloWorldService {
@GET
@Produces("text/html")
public String getClichedMessage() {
return "<h1>Hello Jersey</h1>";
}
}
当我点击浏览器中的网址时,它会按预期显示以下结果:
Hello Jersey
现在,我想在我的jquery中使用相同的HTMl响应,但是我没有得到预期的结果。 警报显示错误状态。请参阅jquery代码,请帮我解决。
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: "GET",
url:"http://localhost:8080/RestTest/rest/hello/",
success:function(result){
$("#div1").html(result);
},
dataType:"html",
error:function(request,status,exception) {
alert(status);
},
complete:function(request,status) {alert("CALL Complete>>>>>>>>>>>>> "+status)}
});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
答案 0 :(得分:0)
您调用的网址很可能不正确。
您的网址以rest/hello/
结尾/
,使其成为rest/hello
的不同网址,因此找不到该路线。
尝试将您的网址更改为:RestTest/rest/hello
- 或与您网页相同的相对网址,只需删除跟踪/
。
此外 - 与网站位于同一域的其他服务是什么? I.E是您的网站位于http://localhost:8080/
?如果没有,它可能是一个跨域问题 - 如果不知道完整的错误消息很难说。
答案 1 :(得分:0)
如果您希望在同一个域上强制crossDomain
请求(例如JSONP),请将crossDomain的值设置为true。
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: "GET",
url:"http://localhost:8080/RestTest/rest/hello/",
crossDomain: true,
success:function(result){
$("#div1").html(result);
},
dataType:"html",
error:function(request,status,exception) {
alert(status);
},
complete:function(request,status) {alert("CALL Complete>>>>>>>>>>>>> "+status)}
});
});
});