我正在使用其他Web服务开发Web应用程序。我试图从ajax调用简单的Web服务。但我没有得到理想的输出。 我的网络服务代码是:
@Path("hello")
public class Hello {
@GET
@Path("/first")
@Produces("text/html")
public String function1(){
return "Something happens";
}
}
我的html文件为休息网络服务提供了ajax调用:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function callme(){
alert("hello");
$.ajax({
type: "GET",
url: "http://localhost:8080/WebApplication4/webresources/hello/first",
data:"",
dataType:"text",
contentType: "text/html",
success: function(resp){alert("Server says" + resp);},
error: function(e){ alert("An error has occured");},
});
}
</script>
</head>
<body>
<form id="form1" method="GET" onsubmit="callme();">
<input type="text" name="t1">
<input type="submit" Value="SUBMIT">
</form>
</body>
</html>
当我从浏览器调用Web服务时,我的Web服务会按预期提供返回值。
我将浏览器中的Web服务称为http://localhost:8080/WebApplication4/webresources/hello/first
并返回文字"Something happens"
ajax调用出了什么问题?
还有如何在ajax中捕获返回的json对象?
谢谢
答案 0 :(得分:3)
这是正确的方法。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function callme(){
alert("hello");
$.ajax({
type: "GET",
url: "https://localhost/codeTest.php",
data:"",
dataType:"text",
contentType: "text/html",
success: function(resp){alert("Server says" + resp);},
error: function(e){ alert("An error has occured");},
});
}
</script>
</head>
<body>
<form id="form1" method="GET">
<input type="text" name="t1">
<input type="button" Value="SUBMIT" onclick="callme();">
</form>
</body>
ajax调用必须来自html输入类型按钮单击事件,而不是表单提交。表单提交事件重新加载页面,它不等待ajax响应。