jquery.post()

jar包:
json-lib-2.2.3-jdk15.jar
struts2-json-plugin-2.3.4.1.jar(此包版本必须和Struts2版本对应,否则会抛错)
-----------------------------------------------------------默默无闻的分割线-----------------------------------------------------------
js文件:
query-1.7.js和json2.js。
-----------------------------------------------------------默默无闻的分割线-----------------------------------------------------------
页面导入js文件路径:
<script language="javascript" src="scripts/javascript/jquery-1.7.js"></script>
<script language="javascript" src="scripts/javascript/json2.js"></script>
-----------------------------------------------------------默默无闻的分割线-----------------------------------------------------------
js函数:
function checkUserName(){
var url='checkUserName';
var params={
    studentName:'1'
};
$.post(
    url,
    params,
    function callback(json){
        var responseData = eval(json);
        var result = responseData.ckUserName;
        if(result=="pass"){
            $("h1").text("pass");
        }else{
            $("h1").text("npass");
        }
    },
    'json'
    ); 
}
-----------------------------------------------------------默默无闻的分割线-----------------------------------------------------------
配置Struts2.xml:
        <action name="checkUserName" class="com.shenzhen.management.action.HelloWorldAjaxAction" method = "checkUserName">
<result type="json">
<param name="#root">ckUserName</param>
</result>
</action>
-----------------------------------------------------------默默无闻的分割线-----------------------------------------------------------
Action方法(通过Spring注入Service接口抛异常,所以另外写了一个HelloWorldAjaxAction.java文件):
public String checkUserName()
{
    String retStr = "fail";
   //通过Spring注入Service接口抛异常,未找到原因,现通过ApplicationContext获取bean,知道如何解决的大神请留言,谢谢!
    ServletContext servletContext = ServletActionContext.getServletContext();
    ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    StudentService studentService = (StudentService)applicationContext.getBean("studentService");
    try{
        ckUserName = "pass";
        retStr = "success";
    }catch(Exception e){
            ckUserName = "npass";
    }
    return retStr;
}

猜你喜欢

转载自isiah-zhou.iteye.com/blog/2293524