js回掉函数取不到action字段的问题

来源:互联网 发布:java 适配器模式 编辑:程序博客网 时间:2024/06/02 02:31

一、问题描述

js与action之间传值出现问题。在struts2的action中成功拿到service层的数据,但是将值传入jsp时出现问题。

action中字段:

@Autowiredprivate User user;
有getter,setter方法。

js代码如下:

 <script type="text/javascript">      $().ready(function(){          $(":button").click(function () {              $.post("User_select",{                  result:"hahahaha"              },function(data){//                  result = eval("(" + data + ")").result;                  alert(data.user.name);              });          });      });    </script>


报错内容:页面报错

Cannot read property 'name' of undefined


二、解决步骤

1.一头雾水的错误。

首先检查了在action中能成功打印user.name

然后检查了struts.xml文件,其中extends和result type的配置也没有错误。

<package name="user" namespace="/" extends="json-default">        <action name="User_*" class="userAction" method="{1}">            <result type="json"></result>            <!--<result name="paramInject">test1.jsp</result>-->        </action>    </package>
js代码块只是一个简单的函数,也没有语法错误,并能成功访问action。

那逻辑上是没有问题的,只是不懂味什么前端取不到action的值。


2.考虑会不会是因为spring注解生成的实例和struts生成的成员属性的实例不是同一个,所以取不到成员属性的值。

将@Autowired注解注释掉,就成功获得了action中的值。


3.回想起前两天进行struts2和spring的整合后,后台传值都没有问题,只有jsp无法使用jstl表达式获取action中的成员属性。会不会也是因为@Autowired的问题。

去掉@Autowired注解后,使用${user.name}就能通过getter,setter方法获得action中的值了。


4.只是@Autowired的问题吗?

将spring的ApplicationContext.xml文件中手动配置action的bean和其中的property子节点

 <bean id="user" class="cn.chan.entity.User"></bean>    <bean id="userAction" class="cn.chan.action.UserAction" scope="prototype">     <property name="model" ref="user"></property>    </bean>
这样同样会使jsp取不到action中的值。


5.结论:在使用spring依赖注入的时候创建的实例,会和sturts2底层创建成员属性实例冲突。两者创建的不是同一个实例,因此jsp无法拿到正确的action中成员属性的实例对象。切记在action中和前端进行参数传递的时候不要将相应的字段使用spring的依赖注入。如何解决这一问题的方法目前还没找到,了解后再记录。


阅读全文
0 0