未捕获的Ext.Error:您正尝试使用Ext JS和Spring MVC解码无效的JSON字符串:表单提交
问题内容:
提交Ext JS表单后,出现以下错误:
未捕获的Ext.Error:您正在尝试解码无效的JSON字符串
JS:
Ext.onReady(function() {
var simple = Ext.create('Ext.form.Panel', {
frame : true,
title : 'Login Form',
bodyStyle : 'padding:5px 5px 0',
width : 350,
fieldDefaults : {
msgTarget : 'side',
labelWidth : 75
},
defaultType : 'textfield',
defaults : {
anchor : '100%'
},
items : [{
fieldLabel : 'User Name',
name : 'userName',
allowBlank : false,
emptyText : 'UserName'
}, {
fieldLabel : 'Password',
name : 'password',
allowBlank : false,
inputType : 'password',
emptyText : 'Password'
}],
buttons : [{
text : 'Save',
handler : function() {
var form = this.up('form').getForm();
form.submit({
url : saveFormUrl
// waitMsg : 'Sending the info...',
// success : function(fp, o) {
// Ext.Msg.alert('Success',
// 'Form submitted.');
// }
});
}
}, {
text : 'Cancel'
}]
});
simple.render(document.body);
simple.getEl().center();
});
控制器类:
@Controller
public class UserController {
private static final Logger logger = LoggerFactory
.getLogger(TController.class);
private TService tService = null;
@Autowired
public void setTService(TService tService) {
this.tService = tService;
}
@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String home() {
System.out.println("Welcome home!");
return "login";
}
@RequestMapping(value = "/save-form.html", method = RequestMethod.POST)
public ModelAndView submitData(User user){
System.out.println("User name:"+user.getUserName());
ModelAndView mv = new ModelAndView("htmlLinks");
return mv;
}
save-form.html:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<html>
<head>
<title>POC</title>
</head>
<body>
Welcome User !!
</body>
</html>
我究竟做错了什么?解决办法是什么?我正在使用Ext JS 4和Spring MVC。
问题答案:
根据该文档的form.submit
,它看起来像在响应 要求
是JSON或XML,格式如下所示:
{
success: true,
data: {
url: "http://somewhere",
someData: "whatever you want"
}
}
在JavaScript的成功处理程序中,您可以引用o.data.[variable]
以获取自定义数据。
不幸的是,您将需要更改submitData method
(在您的控制器中)以按照上面定义的结构返回JSON响应对象。在响应对象中,您可以包含的URL
save-form.html
。然后,您可以在成功处理程序中为其发出另一个GET请求。
我不知道这是否行得通,因为我没有使用Ext JS的经验,但是我会设想成功处理程序看起来像这样:
success: function(fp, o) {
Ext.Msg.alert('Success', 'Form submitted.');
Ext.Ajax.request({
url: o.data.url,
method: "GET",
success: function(response, request) {
// do whatever you need to with the generated HTML
alert(response.responseText);
},
failure: function(response, request) {
alert('failed');
}
});
}