欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ajax提交到java后台之后处理数据的实现

程序员文章站 2022-06-24 16:09:50
环境:eclipse+struts 要实现的效果:点击按钮提交数据到后台之后回到前台显示出来数据 index.jsp <%@ page lang...

环境: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"> 
<div id="msg"></div> 
</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; 
  } 
} 

以上这篇ajax提交到java后台之后处理数据的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。