-1
我是新來的ajax,並希望從行動類到jsp的數據。如何使用struts2中的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代碼。
我也試試這個代碼。 response.setContentType(「text/plain」); response.setCharacterEncoding(「UTF-8」); response.getWriter()。write(name); –
@ParthPatel這將完全起作用。 – udaybhaskar
Thanx @udaybhaskar。 我將「成功」更改爲「無效」,它的工作原理。 你能解釋一下爲什麼「null」的結果類型? –