jquery ajax object调用后台方法问题,返回object

jquery ajax调用 后台方法返回值 问题
[问题点数:20分,结帖人dxd0128]
jquery ajax调用 后台方法返回值 问题
[问题点数:20分,结帖人dxd0128]
只显示楼主
取消只显示楼主
相关帖子推荐:
本帖子已过去太久远了,不再提供回复功能。Jquery跨域调用struts2的Action返回json数据易出现的问题 - blackhost - ITeye技术网站
博客分类:
最近一个项目使用到了JQuery调用Struts2的Action返回的json数据,因为涉及到跨域的操作,所以选择对跨域操作已经做了很好兼容的getJson方法,但实际应用中发现前端也买年的jquery虽然可以调用后台Action类成功,但总是无法调用回调函数!
经过不断的查找,最终确定原因所在,原来跨域调用想要成功调用回调函数,必须是服务器端明确知道回调函数的地址,因此有两个必须的要素要注意:
1、调用的URL必须有callback=?,这个名字可以自己起,不一定叫这个,但是必须有
2、struts2的配置文件里,必须加上 &paramname="callbackParameter"&jsoncallback&/param&
这里面的这个回调参数名称,也好前端传过来的一致。
下面贴出我的使用到的代码片段:
前端页面:
$.getJSON('http://xxxxxxx.xhtml?'+$('#regForm').serialize()+"&jsoncallback=?", function(data) {
alert(data);&&&
后端的struts-json.xml标定返回值部分,注意要包含在result段里
&result name="jsonres" type="json"&
&param name="callbackParameter"&jsoncallback&/param&
&/result&
其它的参照网上struts2对json数据的封装写法即可,最好采用annotion的那种方式
浏览: 5443 次
&div class=&quote_title ...
直接换成64位的JDK。也不建议把一个JVM设置的过大。1)在 ...
首先jvm的内存肯定不能开得太大,太大反而会导致应用暂停问题。 ...
可能楼主还想在服务器安装一个魔兽世界玩玩,所以就。。。。。要3 ...
LZ的想法是可行的,曾经使用过类似部署方法。
服务器操作系统是 ...function Open() {
if ($("#FileUpload").val() != "") {
$.get('VerAdd.aspx?operate=Open&filePath=' + $("#FileUpload").val(), function (info) {
//info.XXX
}, 'json');
alert("请选择文件呀,亲!");
protected void Page_Load(object sender, EventArgs e)
if (Request.QueryString["operate"] != null)
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
switch (Request.QueryString["operate"])
case "Open":
Open(Request.QueryString["filePath"]);
Response.End();
private void Open(string filePath)
string json = "{\'HEXLE\':\'0\',\'BINLE\':\'83512\',\'FIRVER\':\'0100\',\'HARVER\':\'23F0\',\'CRC32\':\'23 F0 12 5C \',\'CRC16\':\'B3 FA \',\'FILELE\':\'83512\',\'BLOCKSUM\':\'82\'}";
Response.Write(json);
最后才发现,json不能为单引号。遂把\' 修改为 \",好了。自己做个笔记。
Views(...) Comments()SpringMVC:整合JQUERY与JSON - 咫尺天涯 - ITeye技术网站
博客分类:
参考资料
1 Spring3 MVC 笔记(二) —json+rest优化
2 jquery 遍历对象、数组、集合
3 jquery 遍历 map(callback)
4& Jquery的map遍历
5 Spring mvc3的ajax
6 Spring MVC 学习笔记 九 json格式的输入和输出
在SpringMVC中使用JSON必须注意二点
1 必须包含:jackson的jar包,我使用的是: jackson-all-1.8.1.jar,
可在官网:中去下载
2 在springmvc.xml配置文件中必配置: &mvc:annotation-driven/&
3 jquery.json-*.*.min.js
实现功能: 从后台获取对象,List,Map在前台显示,前台提交JSON数据格式到后台并且返回
一 工程相关图片
1 工程图片
2 效果图片
二 具体代码
1 springmvc.xml
&?xml version="1.0" encoding="UTF-8" ?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"&
自动搜索@Controller标注的类
用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。
&context:component-scan base-package="com.liuzd.sj.web" /&
&mvc:annotation-driven/&
③:对模型视图名称的解析,即在模型视图名称添加前后缀 --&
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /&
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&
&property name="messageConverters"&
class="org.springframework.http.converter.StringHttpMessageConverter"&
&property name="supportedMediaTypes"&
&value&text/charset=UTF-8&/value&
&/property&
&/property&
&bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /&
2 springmvc与jquery整合页面
&%@ page language="java" contentType="text/ charset=UTF-8"
pageEncoding="UTF-8"%&
&%@ taglib uri="/jsp/jstl/core" prefix="c" %&
&!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&
&meta http-equiv="Content-Type" content="text/ charset=UTF-8"&
&script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"&&/script&
&title&Spring MVC - jQuery 整合教程&/title&
&h3&Spring MVC - jQuery 整合教程&/h3&
&h4&AJAX version&/h4&
&p&Demo 1 计算并返回值&/p&
&div style="border: 1px solid # width: 250"&
Add Two Numbers: &br/&
&input id="inputNumber1" type="text" size="5"& +
&input id="inputNumber2" type="text" size="9"&
&input type="submit" id="demo1" value="Add" /& &br/&
&span id="sum"&(Result will be shown here)&/span&
&p&Demo 2 获取一个对象&/p&
&div style="border: 1px solid # width: 250"&
&select id="userId"&
&c:forEach var="index" begin="1" end="5" step="1"&
&option value="${index}"&${index}&/option&
&/c:forEach&
&input type="submit" id="demo2" value="Get" /& &br/&
&span id="info"&(Result will be shown here)&/span&
&p&Demo 3 返回List集合对象&/p&
&div style="border: 1px solid # width: 250"&
&input type="submit" id="demo3" value="Get List User" /& &br/&
&span id="listInfo"&(Result will be shown here)&/span&
&p&Demo 4 返回Map集合对象&/p&
&div style="border: 1px solid # width: 250"&
&input type="submit" id="demo4" value="Get Map User" /& &br/&
&span id="mapInfo"&(Result will be shown here)&/span&
&a href="${pageContext.request.contextPath}/index.jsp"&返回&/a&
&script type="text/javascript"&
$(function() {
$("#demo1").click(function(){
$.post("${pageContext.request.contextPath}/main/ajax/add.do",
{inputNumber1:
$("#inputNumber1").val(),
inputNumber2:
$("#inputNumber2").val()
function(data){
$("#sum").replaceWith('&span id="sum"&'+ data + '&/span&');
$("#demo2").click(function(){
var userId = $("#userId").val();
$.post("${pageContext.request.contextPath}/main/ajax/getUser/"+userId+".do",
function(data){
var info = "姓名: " + data.name+",年龄: " + data.age + ",地址: " + data.address + ",性别: " + (data.sex == 1 ? "男" : "女")+",密码: " + data.
$("#info").html(info);
$("#demo3").click(function(){
$.post("${pageContext.request.contextPath}/main/ajax/userList.do",
function(data){
var info = '';
var leng = data.
for(var i=0;i&i++){
info += data[i].id + "," + data[i].name + "," + data[i].sex + "," + data[i].password + "," + data[i].address + "," + data[i].age+"&br&";
$("#listInfo").html(info); */
var info = '';
$.each(data,function(index,entity) {
info += "姓名: " + entity.name+",年龄: " + entity.age + ",地址: " + entity.address + ",性别: " + (entity.sex == 1 ? "男" : "女")+",密码: " + entity.password+"&br&";
$("#listInfo").html(info);
$("#demo4").click(function(){
$.post("${pageContext.request.contextPath}/main/ajax/userMap.do",
function(map){
var info = '';
$.each(map,function(key,values) {
info += "key="+key+"&br&";
$(values).each(function(){
info += "姓名: " + this.name+",年龄: " + this.age + ",地址: " + this.address + ",性别: " + (this.sex == 1 ? "男" : "女")+",密码: " + this.password+"&br&";
$("#mapInfo").html(info);
3 springmvc与jquery整合后台代码
package com.liuzd.sj.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import org.springframework.stereotype.C
import org.springframework.web.bind.annotation.PathV
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestP
import org.springframework.web.bind.annotation.ResponseB
import com.liuzd.sj.entity.U
@Controller
@RequestMapping("/main/ajax")
public class AjaxController {
* 根据映射跳转到指定的页面
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAjaxAddPage() {
// 解析 /WEB-INF/jsp/ajax-add-page.jsp
return "ajax-add-page";
* 提交表单并进行运算.
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody Integer add(
@RequestParam(value = "inputNumber1", required = true)Integer inputNumber1,
@RequestParam(value = "inputNumber2", required = true)Integer inputNumber2) {
// 实现运算
Integer sum = inputNumber1 + inputNumber2;
System.out.println("sum: " + sum);
// @ResponseBody 会自动的将返回值转换成JSON格式
// 但是你必须添加jackson的jar包!!!
@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.POST)
public @ResponseBody User getUser(@PathVariable("userId")String
System.out.println("根据ID获取用户对象: " + userId);
Map&String,User& users = new HashMap&String,User&();
users.put("1", new User("123456", "李逵", "123", "成都市", "1", 23));
users.put("2", new User("565676", "张三", "123", "北京市", "2", 53));
users.put("3", new User("325566", "李四", "123", "河南省", "2", 93));
users.put("4", new User("989654", "刘邦", "123", "蒙古包", "1", 13));
users.put("5", new User("234444", "王熙凤", "123", "成都市", "1", 43));
return users.get(userId);
@RequestMapping(value = "/userList", method = RequestMethod.POST)
public @ResponseBody
List&User& getUsers() {
List&User& users = new ArrayList&User&();
users.add(new User("123456", "李逵", "123", "成都市", "1", 23));
users.add(new User("123457", "李四", "124", "北京市", "2", 53));
users.add(new User("123458", "李三", "125", "河南市", "0", 73));
users.add(new User("123459", "李五", "126", "大路市", "3", 93));
@RequestMapping(value = "/userMap", method = RequestMethod.POST)
public @ResponseBody Map&String,User& getUserMap() {
Map&String,User& users = new HashMap&String,User&();
users.put("1", new User("123456", "李逵", "123", "成都市", "1", 23));
users.put("2",new User("123457", "李四", "124", "北京市", "2", 53));
users.put("3",new User("123458", "李三", "125", "河南市", "0", 73));
users.put("4",new User("123459", "李五", "126", "大路市", "3", 93));
4 sprinmcv与jquery,json整合页面
&%@ page language="java" contentType="text/ charset=UTF-8"
pageEncoding="UTF-8"%&
&%@ taglib uri="/jsp/jstl/core" prefix="c" %&
&!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&
&meta http-equiv="Content-Type" content="text/ charset=UTF-8"&
&title&Spring MVC&/title&
&script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"&&/script&
&script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery.json-2.2.min.js"&&/script&
&script type="text/javascript"&
$(document).ready(function(){
jQuery.ajax( {
type : 'GET',
contentType : 'application/json',
url : '${pageContext.request.contextPath}/user/list.do',
dataType : 'json',
success : function(data) {
if (data && data.success == "true") {
$('#info').html("共" + data.total + "条数据。&br/&");
$.each(data.data, function(i, item) {
$('#info').append("编号:" + item.id + ",姓名:" + item.name + ",年龄:" + item.age+"&br&");
error : function() {
alert("error")
$("#submit").click(function() {
var jsonuserinfo = $.toJSON($('#form').serializeObject());
alert(jsonuserinfo);
jQuery.ajax( {
type : 'POST',
contentType : 'application/json',
url : '${pageContext.request.contextPath}/user/add.do',
data : jsonuserinfo,
dataType : 'json',
success : function(data) {
if (data && data.success == "true") {
$('#info').html("共" + data.total + "条数据。&br/&");
$.each(data.data, function(i, item) {
$('#info').append("编号:" + item.id + ",姓名:" + item.name + ",年龄:" + item.age+"&br&");
alert("新增成功!");
error : function(data) {
alert("error")
//将一个表单的数据返回成JSON对象
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
o[this.name].push(this.value || '');
o[this.name] = this.value || '';
&div id="info"&&/div&
&form action="add" method="post" id="form"&
编号:&input type="text" name="id"/&
姓名:&input type="text" name="name"/&
年龄:&input type="text" name="age"/&
性别: &select name="sex"&
&option value="1"&男&/option&
&option value="2"&女&/option&
密码: &input name="password"&
地址:&input name="address"/&
&input type="button" value="提交" id="submit"/&
5 sprinmcv与jquery,json后台代码
package com.liuzd.sj.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import org.springframework.http.HttpE
import org.springframework.stereotype.C
import org.springframework.web.bind.annotation.ModelA
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.ResponseB
import org.springframework.web.bind.annotation.SessionA
import com.liuzd.sj.entity.U
@Controller
@RequestMapping("/user")
@SessionAttributes("users")
public class DemoController {
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ModelAttribute("users")
@ResponseBody
public Map&String, Object& getUserMaps() {
List&User& list = new ArrayList&User&();
User um = new User();
um.setId("1");
um.setName("sss");
um.setAge(66);
list.add(um);
um = new User();
um.setId("2");
um.setName("aaa");
um.setAge(44);
list.add(um);
Map&String, Object& modelMap = new HashMap&String, Object&();
modelMap.put("total", list.size());
modelMap.put("data", list);
modelMap.put("success", "true");
return modelM
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
//二种方式: A HttpEntity&User&
B使用注解 @ResponseBody
public Map&String, Object& addUser(HttpEntity&User& model,javax.servlet.http.HttpServletRequest request) {
System.out.println("user: " + model.getBody());
Map&String, Object& map = (Map)request.getSession().getAttribute("users");
if(null == map){
map = getUserMaps();
List&User& list = (List&User&)map.get("data");
list.add(model.getBody());
map.put("total", list.size());
map.put("data", list);
request.getSession().setAttribute("users",map);
@RequestMapping("/ajaxPage")
public String ajaxAddPage() {
return "ajax-add-page2";
&?xml version="1.0" encoding="UTF-8"?&
&web-app version="2.4" xmlns="/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="/xml/ns/j2ee
/xml/ns/j2ee/web-app_2_4.xsd"&
&context-param&
&param-name&log4jConfigLocation&/param-name&
&param-value&/WEB-INF/classes/log4j.properties&/param-value&
&/context-param&
&context-param&
&param-name&log4jRefreshInterval&/param-name&
&param-value&60000&/param-value&
&/context-param&
&context-param&
&param-name&log4jExposeWebAppRoot&/param-name&
&param-value&false&/param-value&
&/context-param&
&listener&
&listener-class&
org.springframework.web.util.Log4jConfigListener
&/listener-class&
&/listener&
&filter-name&encodingFilter&/filter-name&
&filter-class&
org.springframework.web.filter.CharacterEncodingFilter
&/filter-class&
&init-param&
&param-name&encoding&/param-name&
&param-value&UTF-8&/param-value&
&/init-param&
&init-param&
&param-name&forceEncoding&/param-name&
&param-value&false&/param-value&
&/init-param&
&filter-mapping&
&filter-name&encodingFilter&/filter-name&
&url-pattern&*.do&/url-pattern&
&/filter-mapping&
&filter-mapping&
&filter-name&encodingFilter&/filter-name&
&url-pattern&*.jsp&/url-pattern&
&/filter-mapping&
&servlet-name&springmvc&/servlet-name&
&servlet-class&
org.springframework.web.servlet.DispatcherServlet
&/servlet-class&
&init-param&
&param-name&contextConfigLocation&/param-name&
&param-value&classpath:springmvc.xml&/param-value&
&/init-param&
&load-on-startup&1&/load-on-startup&
&/servlet&
&servlet-mapping&
&servlet-name&springmvc&/servlet-name&
&url-pattern&*.do&/url-pattern&
&/servlet-mapping&
&welcome-file-list&
&welcome-file&index.jsp&/welcome-file&
&/welcome-file-list&
&/web-app&
7 附件为工程原件,只包含jackson-all-1.8.1.jar,其它jar可在相关页面下载
(958.8 KB)
下载次数: 4240
浏览 43019
用了org.springframework.web.filter.CharacterEncodingFilter一般就没有乱码的问题了,你试过吗,请提意见呀 为何注释掉下面这段代码呢?
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&
&property name="messageConverters"&
class="org.springframework.http.converter.StringHttpMessageConverter"&
&property name="supportedMediaTypes"&
&value&text/charset=UTF-8&/value&
&/property&
&/property&
&bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /&
浏览: 784510 次
来自: 成都
写得不错,thx楼主!
为什么不能下载源码?
找了许久,终于找到一个可以运行的,不乱码的,晕……
谢了

我要回帖

更多关于 jquery html object 的文章

 

随机推荐