Layui.自定义验证&Ajax
Ajax检测是否有重复数JavaScript
错误示范(我第一次是这么写的)
//这种方式不可用,哪怕return了提示语,还是会提交表单
//自定义验证规则
form.verify({
submitFormCheckHostName: function (value) {
debugger;
//return value;
if (value) {
var hostName = laylj.string.trim(value);
loadingIndexTemp = laylj.layerMsg.loading();
$.ajax({
type: 'get',
url: "/api/promotionsettinghost/list/hostname",
dataType: "json",
async: false,
data: { "hostName": encodeURIComponent(hostName) },
success: function (mes) {
layer.close(loadingIndexTemp);
if (mes && mes.IsSuccess && mes.Data && mes.Data.length > 0) {
var hostArr = [];
$.each(mes.Data, function (i, item) {
hostArr.push(item.HostName);
})
return "该域名已经存在 " + hostArr.join();
}
}, error: function () {
layer.close(loadingIndexTemp);
}
});
}
}
});
正确写法
//修改后的代码.
//自定义验证规则
form.verify({
submitFormCheckHostName: function (value) {
debugger;
if (value) {
//修改返回项
var checkResult = "";
var hostName = laylj.string.trim(value);
loadingIndexTemp = laylj.layerMsg.loading();
$.ajax({
type: 'get',
url: "/api/promotionsettinghost/list/hostname",
dataType: "json",
async: false,
data: { "hostName": encodeURIComponent(hostName) },
success: function (mes) {
layer.close(loadingIndexTemp);
if (mes && mes.IsSuccess && mes.Data && mes.Data.length > 0) {
var hostArr = [];
$.each(mes.Data, function (i, item) {
hostArr.push(item.HostName);
})
//不直接返回,而是赋值 => checkResult
checkResult = "该域名已经存在 " + hostArr.join();
}
}, error: function () {
layer.close(loadingIndexTemp);
}
});
//最终返回
return checkResult;
}
}
});