怕以后忘记,作为笔记。
UserAction
package action;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
private String value;//后台的属性与ajax发送的数据名一致 有set get
private String url;//返回的值 有get--用于ajax获取
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String test1(){
url="test1";
System.out.println(value);
return SUCCESS;
}
structs2.xml
所谓的JSON就是一种key -value形式的数值格式
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="actions" namespace="/" extends="json-default">
<action name="user" class="action.UserAction" method="test1">
<!-- <result name="success">/1.jsp</result> -->
<!--在stucts2中,type="json"是用来做ajax请求的,所以根本没有@R_593_404@面,Json是一种数据格式,这个result会将action中的变量 转成json返回页面 -->
<result name="success" type="json">
</result>
</action>
</package>
</struts>
jsp:代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<script src="js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript"> $(function(){ $("#button").click(function(){ $.ajax({ type: "GET",url: "user.action",data: {value:"msg"},//形式为key-value dataType: "json",success: function(data){ alert(data.url); },error: function(err) { alert(err); } }); }); }); </script>
</head>
<body>
<input id="button" type="button" value="图书" >
</body>
</html>
结果:
后台收到数据: