Struts2+Jquery+ajax+json结合应用

Jquery ajax代码(采用.post()方法):

var url="UserLogin_login";
var params={"user.id":$("#input_login_email").val(),"user.password":$("#input_login_password").val()};
$.post(url,params,function(data){
			var result= eval("("+data+")");
			//alert(data);
			if(result.loginStatus){
				if(result.name=="null"){
					setCookie(name,result.id,expiredays);
					$("#userShow").html(result.id);
				}
				else
					$("#userShow").html(result.name);
				/*document.getElementById("loginLink").style.display="none";替换如下*/
				$("#loginLink").css("display","none");
				$("#modal-container-login").modal('hide');
			}else{
				$("#span_login_emailWarn").html("账号或密码错误");
				spinner.stop();
			}
		});//$.post

struts.xml:

<action name="*_*" class="com.sanxiau.action.{1}Action"
        method="{2}">
        </action>
说明:<action>中不需要写<result>


action中

public String login(){
        /*测试一下*/
        System.out.println("id="+this.getId()+"password="+this.getPassword());
        applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        userService = (UserService) applicationContext.getBean("UserServiceImpl");
        isSuccess=userService.checkIdAndPassword(id, password);
 
        HttpServletResponse response = ServletActionContext.getResponse();  
        response.setContentType("text/html;charset=UTF-8");     
        response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码    
        PrintWriter writer;
        try {
            writer = response.getWriter();
             String json= "{id:\""+id+"\"}";  
             writer.write(json); 
             System.out.println(json);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
         
        return NONE;
    }

总结:

         给出的是部分代码;

        1,.post方法中url给出XX.action在web.xml中配置了拦截器,然后被actin接受到,post()中第二参数表示传回服务器的值,actin中一定要配置getter方法;

         2,action将要返回页面的数据放到response里面;至于为什么,我不知道,设计的时候我不在场;我只知道post()方法中第三个参数(即回调函数),这个参数也就是方法啦,这个方法的接受到的就是response;

          3,把response eval一下(原理自己百度谷歌吧),然后就得到了JSON格式的数据啦,然后就没有然后了,自己看着办,想怎么用这个json就怎么用


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值