开发者

assign value to global variable in javascript

I want to assign value to global variable in javascript from jquery ajax function.

var trueFalse;
$.ajax({
   type: "GEt",
   url: "url",
   data: "text=" + $("#text").val(), 
   success: function(msg) {
     if(msg.match(/OK/) != null) {
       trueFalse = "true";
     }
     else {
       trueFalse = "false";         
     }
   }
});
return trueFals开发者_Go百科e;

here i need the value of trueFalse from success function.

thanks v.srinath


Your code won't work because the line return trueFalse; executes before the success function runs, since it is called as the result of an asynchronous (as in the A in Ajax) HTTP request. You would need to pass in a callback function to this code, and invoke that in the success function:

function getWithCallback(val, callback) {
    var scope = this;
    $.ajax({
        type: "GET",
        url: "url",
        data: "text=" + val,
        success: function(msg) {
            callback.call(scope, msg.match(/OK/) || false);
        }
    });
}

getWithCallback($("#text").val(), function(result) {
    if (result) {
        // Do something
    }
});

You could try this to validate a form on submit:

var validating = false;
var valid = false;

$('#myform').submit(function(event) {
    if (validating) {
        return false;
    }
    if (valid) {
        return true;
    }
    var form = this;
    validating = true;
    getWithCallback($('#text').val(), function(result) {
        if (result) {
            valid = true;
            form.submit();
        }
        validating = false;
    });
    return false;
});

You might also want to look at the jQuery Validation plugin


If you really can't change the application logic, then you have to create a "synchronous" ajax request (by setting async:false in $.ajax options), then it will wait until the "GET" has executed and only then return the value to the caller.

Otherwise, you should rewrite the code so that the success function calls back into some callback function that it can now proceed with whatever has to be done.


Since you are doing this on form.onsubmit, you cannot do an async request. The browser won't know that it should wait until the async request is finished. The benefit of using async is that it does not lock up your scripts/browser, but in this case that is actually what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜