本文介绍了加载图片显示在点击一个按钮来调用jquery ajax很长的延迟之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在点击按钮上显示一个加载图像,通过ajax验证表单,但加载图像仅在延迟一段时间后显示(上传到服务器时需要2秒以上才能显示图像)。但我想在按钮点击事件的时刻。我的代码如下。

  $(#Save)。click(function(){
//
$(#load_img)。show();
//调用ajax for vaidation
lookUpValidation($ (#item1))
//调用ajax for vaidation
lookUpValidation($(#item2))
})
函数lookUpValidation(this_element,id){
url =/ validate / lookupid /+ id,
lookUpValidationResult = false;
lookUpValidationData = false;
if(this_element.val()!=){
$ .ajax({
url:url,
type:POST,
async: false,
data:{
value:this_element.val()
},
beforeSend:function(data){
//显示加载图像
$(#load_img)。show();
},
complete:function(data){
if(data){
var res = JSON.parse (data.responseText);
lookUpValidationData = res;
if(res.field){
lookUpValidationResult = 1;
}
else
// not找到
lookUpValidationResult = 2;

}
else {
//未找到
lookUpValidationResult = 2;
}
}
});
}
else {
// null
lookUpValidationResult = 3;
}
返回lookUpValidationResult;

HTML

 < div class =k-loading-imageid =load_imgstyle =display:none;> 
< div class =k-loading-color>
< / div>
< / div>


解决方案

对服务器的调用是同步完成的,点击处理程序阻止浏览器显示图像。



据我所知,没有跨浏览器的方式来强制和从JavaScript更新。但是,为了实现这个自定义解决方案,您可能会有一些运气。谷歌搜索应该有助于解决这个问题。



处理这种情况的另一种方法是防止默认处理click事件,并在所有异步验证完成后提交表单

更好的解决方案恕我直言,是在用户填写表单时异步验证每个字段,并且只有在所有验证完成后才启用保存按钮。这可以使用 .blur()来完成,以便在用户移动到下一个输入时验证每个输入。用户输入时的验证可以通过 .keypress() setTimeout()的组合来实现。下面是一个简短的例子:

 <!doctype html> 
< html lang =en>
< head>< / head>
< body>
< form id =formaction =form.html>
< label for =item1>验证模糊邮件:< / label>< input id =item1type =text/>< span id =item1-status >无效< /跨度><峰; br />
< lavel for =item2>在写入时验证电子邮件< / lavel>< input id =item2type =text/>< span id =item2-status>无效< /跨度><峰; br />
< button id =Savetype =submit>储存< /按钮>
< / form>

< script src =http://code.jquery.com/jquery-1.9.1.min.js>< / script>
< script type =text / javascript>
$(function(){
var validState = {
set:function(name,state){
this [name] = state;
updateUI );
},
item1:null,
item2:null
}

function formIsValid(){
var res = true;
for(var name in validState){
res = res&&& validState [name];
}

return res;


$函数validString(val){
返回val == null?
:val?有效:无效

$ b函数updateUI(){
$(#item1-status).text(validString(validState.item1));
$(#item2-status).text (validSate.item2));
$(#Save)。prop(disabled,!formIsValid());
}

函数isEmail(str ){
return /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[AZ]{2,4}\//.test(str) ;


function validateItem1(){
validState.set(item1,isEmail($(#item1)。val()));
}
function validateItem2(){
validState.set(item2,isEmail($(#item2)。val()));
}

//失去焦点后验证
$(#item1)。blur(validateItem1);

//使用超时验证用户何时停止输入
$(#item2)。blur(function(){
var handle = $(this).data (validation-timer);
if(handle)clearTimeout(handle);
validateItem2();
})。 (this);
var handle = self.data(validation-timer);
if(handle)clearTimeout(handle);
var new_handle = setTimeout(validateItem2,1000);
self.data(validation-timer,new_handle);
});

updateUI();
});
< / script>
< / body>
< / html>


I am trying to show a loading image on a button click that will validate a form via ajax, but the loading image shows only after some delay (when uploaded to server it takes more than 2 seconds to show the image). But I want it in the moment of button click event. My code is given below.

$("#Save").click(function() {
    // shows theloading image (here I am expecting the loading image, it never shows.)
    $("#load_img").show();  
    // calls ajax for vaidation
    lookUpValidation($("#item1")) 
    // calls ajax for vaidation
    lookUpValidation($("#item2"))
})
function lookUpValidation(this_element,id) {
    url = "/validate/lookupid/"+id,
    lookUpValidationResult  = false;
    lookUpValidationData    = false;    
    if(this_element.val()!="") {
        $.ajax({
            url : url,
            type : "POST",
            async : false,
            data : {    
                "value"   : this_element.val()
            },      
            beforeSend : function(data) {
                // shows theloading image
                $("#load_img").show();
            },
            complete : function(data) {             
                if(data) {
                    var res = JSON.parse(data.responseText);
                    lookUpValidationData = res;
                        if(res.field) {    
                            lookUpValidationResult = 1;
                        }
                        else
                            // not found
                            lookUpValidationResult = 2;

                    }
                    else {
                        // not found
                        lookUpValidationResult = 2;
                    }       
                }
            });
        }
        else {
            // null
            lookUpValidationResult = 3;
        }
        return lookUpValidationResult;
}

HTML

<div class="k-loading-image" id="load_img" style="display:none;">
    <div class="k-loading-color">
    </div>
</div>
解决方案

The call to the server is done synchronously, so the click handler blocks the browser from showing the image.

To my knowledge there is no cross-browser way to force and ui update from javascript. But you may have some luck with implemting a custom solution for this. A google search should assist in this.

Another way to handle this would be to prevent the default handling of the click event, and to submit the form after all async validation has succeeded.

The better solution IMHO is to validate each field asynchronously while the user is filling in the form and only enable the save button when all validation has been completed. This can be done using .blur() so that each input is validated when the user moves to the next one. Validation while the user is typing could be implemented by a combination of .keypress() and setTimeout(). Here is a short example illustrating this:

<!doctype html>
<html lang="en">
<head></head>
<body>
    <form id="form" action="form.html">
        <label for="item1">Validate email on blur:</label><input id="item1" type="text"/><span id="item1-status">Invalid</span><br/>
        <lavel for="item2">Validate email while writing</lavel><input id="item2" type="text"/><span id="item2-status">Invalid</span><br/>
        <button id="Save" type="submit">Save</button>
    </form>

    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
    $(function () {
        var validState = {
            "set": function (name, state) {
                this[name] = state;
                updateUI();
            },
            "item1": null,
            "item2": null
        }

        function formIsValid() {
            var res = true;
            for(var name in validState) {
                res = res && validState[name];
            }

            return res;
        }

        function validString(val) {
            return val==null ? ""
                : val ? "Valid" : "Invalid"
        }

        function updateUI() {
            $("#item1-status").text( validString(validState.item1) );
            $("#item2-status").text( validString(validState.item2) );
            $("#Save").prop("disabled", !formIsValid());
        }

        function isEmail(str) {
            return /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i.test(str);
        }

        function validateItem1() {
            validState.set("item1", isEmail($("#item1").val()));
        }
        function validateItem2() {
            validState.set("item2", isEmail($("#item2").val()));
        }

        // Validate after loosing focus
        $("#item1").blur(validateItem1);

        // Use timeout to validate when user has stopped typing
        $("#item2").blur(function() {
            var handle = $(this).data("validation-timer");
            if( handle ) clearTimeout(handle);
            validateItem2();
        }).keydown(function () {
            var self = $(this);
            var handle = self.data("validation-timer");
            if( handle ) clearTimeout(handle);
            var new_handle = setTimeout(validateItem2, 1000);
            self.data("validation-timer", new_handle);
        });

        updateUI();
    });
    </script>
</body>
</html>

这篇关于加载图片显示在点击一个按钮来调用jquery ajax很长的延迟之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 23:03