Java AJAX变量传递

问题描述:

我有一个java文件,我想通过它使用AJAX将jsp文件传递给像{{:id:5,GPA:5}}这样的文件。我使用下面的代码是:Java AJAX变量传递

在我的JAVA文件:

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { 
      JSONObject jsonResult = new JSONObject(); 
      jsonResult.put("id", "5"); 
      jsonResult.put("GPA", "5"); 

      response.setContentType("application/json"); 
      response.setCharacterEncoding("UTF-8"); 
      response.getWriter().write(jsonResult.toString()); 
} 

在JSP文件: - 有些ExtJS的代码 -

Ext.Ajax.request({ 
      url :'assertion.htm', 
      method : 'POST', 
      params: { 
        existingRule : nameField.getRawValue() 
      }, 
      scope : this, 
      success: function (response) { 
       alert(response.responseText); 
      } 

response.responseText是打印整个JSP文件而不是打印id:5,GPA:5 任何人都可以帮助我吗?

+0

重新标记,因为你似乎是使用Spring MVC – 2011-05-04 12:09:33

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { 
      JSONObject jsonResult = new JSONObject(); 
      jsonResult.put("id", "5"); 
      jsonResult.put("GPA", "5"); 

      response.setContentType("application/json"); 
      response.setCharacterEncoding("UTF-8"); 
      response.getWriter().write(jsonResult.toString()); 
} 

这不会编译,你是缺少一个return语句。

这似乎是一个Spring MVC控制器,由ModelAndView返回类型来判断。我的猜测是你要返回一个JSP视图,而不是你想要返回的JSON对象。有关如何从Spring MVC返回JSON对象,请参见this previous question of mine

+0

我很抱歉,但我已经加入return语句 ModelAndView的MAV =新ModelAndView(“AssertionScreen”,“AssertRules”,“A”); return mav; – Sapan 2011-05-04 12:34:50

你的函数不返回任何东西,这是正确的,从而将其更改为无效:

protected void handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { 
      JSONObject jsonResult = new JSONObject(); 
      jsonResult.put("id", "5"); 
      jsonResult.put("GPA", "5"); 

      response.setContentType("application/json"); 
      response.setCharacterEncoding("UTF-8"); 
      response.getWriter().write(jsonResult.toString()); 
}