Welcome to Jonic Developer Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

layui 弹窗关闭问题

一个弹出层,有个“确定”按钮,点击确认的时候,有个请求,这时候不希望立即关闭窗口,而是根据接口返回的结果来判断是否要关闭窗口

根据官方文档提示,只要在回调函数里面return false 就不会关闭窗口,

layer.open({
       btn: ['取消', '确认'],
   
       btn2: function(index, layero){
     
        var result = false;

        $.ajax({
            url: "xxxx",
            type: "POST",
            contentType: 'application/json',
            dataType: "json",
            data: JSON.stringify({email: email, code:code, password:password}),
            success: function(res){
                if (res.code == 401) {
                    result= false;
                }else if(res.code == 200){
                     result= true;
                };
            },
        });
        return result;

但是我发现 return result 在 ajax 请求还没返回结果时,result result 先执行了,所以一直返回false导致无法关闭


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

因为 ajax 是异步请求,这里并不会阻塞等待他执行完成,可以使用 layer.close来处理。

layer.open 会返回一个资源ID,在 ajax 的结果中使用 layer.close(资源ID) 来关闭弹窗。

- layer.open({
+ window.dialog1 = layer.open({
    btn: ['取消', '确认'],

    btn2: function(index, layero){

    var result = false;

    $.ajax({
        url: "xxxx",
        type: "POST",
        contentType: 'application/json',
        dataType: "json",
        data: JSON.stringify({email: email, code:code, password:password}),
        success: function(res){
            if (res.code == 401) {
                result= false;
            }else if(res.code == 200){
                 result= true;
            };
+            if(result && window.dialog1){
+                layer.close(dialog1);
+            }
        },
    });
    return result;
+ }});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Jonic Developer Community for programmer and developer-Open, Learning and Share
...