我是ajax的新手,想要从动作类获取数据到jsp。
文件: getRole.jsp
<head>
<script type="text/javascript">
var request;
function loaddata()
{
var id = document.getElementById("newRole").value;
alert("hi : "+ id);
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("display_info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "loadData?id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<label for="focusedInput" id="abc"><h4>Enter Id : </h4></label>
<input type="text" class="form-control" name="newRole" id="newRole" onkeyup="loaddata();">
<div id="display_info" ></div>
</div>
<div class="col-sm-2"></div>
</div>
</body>
文件: loadData.java
public class loadData extends ActionSupport implements ServletRequestAware, ServletResponseAware{
private static final long serialVersionUID = 1L;
String url = "jdbc:mysql://localhost:3306/struts";
String user = "username";
String pass = "password";
HttpServletRequest request;
HttpServletResponse response;
@Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request = request;
}
public HttpServletRequest getServletRequest() {
return request;
}
@Override
public void setServletResponse(HttpServletResponse response) {
// TODO Auto-generated method stub
this.response = response;
}
public HttpServletResponse getServletResponse()
{
return response;
}
public String execute()
{
try{
String id = request.getParameter("id");
String name = "null.";
System.out.println("in servlet : " + id);
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =DriverManager.getConnection(url, user, pass);
String s = "select * from tempemp where id="+id;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(s);
while(rs.next())
{
name = rs.getString("role");
System.out.println(name);
}
PrintWriter out = response.getWriter();
out.println("Name: "+name);
con.close();
}
catch(Exception e){
e.printStackTrace();
}
return SUCCESS;
}
}
我想从用户那里获取Id,然后根据该ID打印角色。 我只想使用ajax而不是json。所以请只回答我ajax代码。
答案 0 :(得分:1)
您必须在操作中返回null
而不是成功。
返回null
将不再进行进一步处理,它只会将当前响应发送给客户端。
返回SUCCESS将在struts.xml文件中搜索为该结果定义的特定jsp页面。
this.responseText
您将获得name
。
更多参考https://struts.apache.org/docs/ajax.html