struts2 ajax jquery返回json类型

三个页面,

<?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="default" namespace="/" extends="json-default">
        <action name="checkuser" class="checkuserAction">
            <result name="success" type="json">
                <param name="root">result</param>
            </result>
        </action>
    </package>
</struts>    
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;

public class checkuserAction extends ActionSupport {
    private String username;
    private JSONObject obj;
    private String result;
    /** * @return */
    public String execute() {
        String msg = "";
        if (username.equals("admin")) {
            msg="已经注册啦,不行";
        }
        else {
            msg="可以注册,放心";
        }
        Map<String,String>  map = new HashMap<String,String>();
        map.put("msg", msg);
        obj=JSONObject.fromObject(map);
        result=obj.toString();
        return SUCCESS;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public JSONObject getObj() {
        return obj;
    }
    public void setObj(JSONObject obj) {
        this.obj = obj;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }

}
<%@ 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>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript"> $(document).ready(function() { $("#username").bind("blur", function() { var username = $("#username").val(); $.ajax({ type : "post", url : "checkuser", dataType : "json", data : { 'username' : username }, success : function(data) { var d = eval("(" + data + ")");//将数据转换成json类型,可以把data用alert()输出出来看看到底是什么样的结构 //得到的d是一个形如{"key":"value","key1":"value1"}的数据类型,然后取值出来 $("#msg").text("" + d.msg + ""); } }); }); }); </script>
</head>

<body>
    <input type="text" name="username" id="username">
    <div id="msg"></div>

</body>
</html>

你可能感兴趣的:(struts2 ajax jquery返回json类型)