昨天下午某項目遇到一個問題,modalDialog內嵌的頁面使用form表單發起ajax請求,原來的代碼是在$.modalDialog組件設置一個提交按鈕,但是奇怪的問題現象是,後臺返回的響應json卻接收不到,於是我就想到了,由於是內嵌的頁面發起form表單請求,響應應該返回到該內嵌頁面才能夠做處理,於是就研究了很長時間,最終問題解決。
先來看下原來的代碼:
var dialog = $.modalDialog({
title : '修改信息',
width : 400,
height : 450,
href : 'edit.jsp',
resizable : true,
onLoad : function() {
var f = $.modalDialog.handler.find("#form");
if (result.rows) {
var data = result.rows[0];
f.form('load', data);
transDetailTemp.edit_currency = data.currency;
transDetailTemp.edit_direction = data.direction;
transDetailTemp.init();
}
},
buttons : [
{
text : '提交',
iconCls:'icon-edit',
handler : function() {
$.modalDialog.openner = $grid;
$('#form').form('submit', {
url: baseUrl+ "/importDetail",
onSubmit: function () { //表單提交前的回調函數
var isValid = $(this).form('validate');//驗證表單中的一些控件的值是否填寫正確,比如某些文本框中的內容必須是數字
if (!isValid) {
}
return isValid; // 如果驗證不通過,返回false終止表單提交
},
success: function (data) { //表單提交成功後的回調函數
$.modalDialog.handler.dialog('destroy');
$.modalDialog.handler = undefined;
$.messager.show({
title : '提示',
msg: data.desc ? data.desc : data.retMsg
});
}
});
}
},
{
text : '取消',
iconCls : 'icon-cancel',
handler : function() {
$.modalDialog.handler.dialog('destroy');
$.modalDialog.handler = undefined;
}
}
]
});
根據上面的代碼我做了調整
var dialog = $.modalDialog({
title : '修改信息',
width : 400,
height : 450,
href : 'edit.jsp',
resizable : true,
onLoad : function() {
var f = $.modalDialog.handler.find("#form");
if (result.rows) {
var data = result.rows[0];
f.form('load', data);
transDetailTemp.edit_currency = data.currency;
transDetailTemp.edit_direction = data.direction;
transDetailTemp.init();
}
},
buttons : [
{
text : '提交修改',
iconCls:'icon-edit',
handler : function() {
$.modalDialog.openner = $grid;
editPlus();
}
},
{
text : '取消',
iconCls : 'icon-cancel',
handler : function() {
$.modalDialog.handler.dialog('destroy');
$.modalDialog.handler = undefined;
}
}
]
});
在edit.jsp頁面我寫了個函數:
function editPlus(){
$.ajax({
type : 'POST',
url : baseUrl+ "/importDetail",
data : JSON.stringify({
transDate : $('#transDate').val(),
transTime : $('#transTime').val(),
flowNo : $('#flowNo').val()
}),
dataType : "json",
contentType : "application/json;charse=UTF-8",
success : function(data) {
$.modalDialog.handler.dialog('destroy');
$.modalDialog.handler = undefined;
$.messager.show({
title : '提示',
msg: data.desc ? data.desc : data.retMsg
});
},
error:function(data){
console.log(data);
alert("網絡錯誤,保存失敗!");
}
});
}
這樣既接收到後臺響應,又可以把對話框關閉,並且彈出我們需要的提示信息。