微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【实例】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">
<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;
	}
}

原文地址:https://www.jb51.cc/ajax/162349.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐