首頁  >  文章  >  web前端  >  ajax提交到java後怎麼處理數據

ajax提交到java後怎麼處理數據

php中世界最好的语言
php中世界最好的语言原創
2018-03-31 15:50:391824瀏覽

這次帶給大家ajax提交到java後怎麼處理數據,ajax提交到java後處理數據的注意事項有哪些,下面就是實戰案例,一起來看一下。

環境:eclipse+struts

#要實現的效果:點擊按鈕提交資料到後台之後回到前台顯示出來資料

index.jsp

#
<%@ page language="java" contentType="text/html; charset=UTF-8" 
  pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
<input type="text" id="userinput"> 
<input type="button" id="submit"> 
<p id="msg"></p> 
</body> 
<script type="text/javascript" src="jquery-2.1.0.js"></script> 
<script type="text/javascript"> 
window.onload = function() { 
  document.getElementById("submit").onclick = test; 
} 
function test(){ 
  var userinput = document.getElementById("userinput"); 
  $.post("http://localhost:8080/TestSpring/TestAction",{username:userinput.value}, 
  function(data, textStatus){ 
    document.getElementById("msg").innerHTML = data; 
  });  
} 
</script> 
</html>

 struts.xml##

<action name="TestAction" class="com.action.Test"> 
  <result>index.jsp</result> 
</action>

Test.java

package com.action; 
 
import java.io.PrintWriter; 
import java.util.Map; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import org.apache.struts2.ServletActionContext; 
 
import com.opensymphony.xwork2.ActionContext; 
import com.opensymphony.xwork2.ActionSupport; 
 
public class Test extends ActionSupport { 
  @Override 
  public String execute() throws Exception { 
    // TODO Auto-generated method stub 
    HttpServletRequest request = org.apache.struts2.ServletActionContext.getRequest(); 
    HttpServletResponse response = ServletActionContext.getResponse(); 
    request.setCharacterEncoding("utf-8"); 
    response.setCharacterEncoding("utf-8"); 
    PrintWriter out = response.getWriter(); 
    out.write(request.getParameter("username")); 
    out.flush(); 
    out.close(); 
    return SUCCESS; 
  } 
}
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

怎麼用ajax實作提交評論並自動刷新

怎麼讓瀏覽器記住ajax請求並控制瀏覽器前進與後退
#

以上是ajax提交到java後怎麼處理數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn