开发者

In IE7 how do I set a global variable or element value using an ajax call during a jquery .click event?

In IE7, when this code is called in the .submittable click event, I have to click the submit button twice to get the orderCount global variable to be set. Or if I set an attribute value on a hidden tag, I get the same experience. For the element value to be set I have to click the button twice. It's like I need to give the browser more time to process. Any suggetions ? Thank You, Nate

var orderCount = 0;
$(document).ready(function(){
$('.submittable').click(function(){
        setOrderCount()
        if ( orderCount == 0 ){
            if (validateAcknowledment($(this).attr('id'))){
                acknowledgeDay($(this).attr('id'));
            }       
        }
    });
});
function setOrderCount(){

    // move this up to validate and do a setAtr
    var scho开发者_C百科ol = $("#school").val();
    var orderDate = $("#orderDate").val();
    $.ajax({
        url: "/fos/inventory/getPreviousWeeklyMenuOrders",
        type: "GET",
        dataType: 'json',
        cache:false,
        data: {school: school,
            startWeekMonth: Date.parse(orderDate).getMonth(),
            startWeekDay: Date.parse(orderDate).getDate(),
            startWeekYear: Date.parse(orderDate).getFullYear()
        },
        success: function(data) {

            orderCount = data.orderCount;
            if(orderCount > 0){
                showErrorMessage("You must Acknowledge prior Weekly Menu Order(s) before acknowledging this week's order", 200, 300);
            }

        }
});


it's amazing how many of these questions come up.

By default the AJAX call is asnychronous. You initiate the call on your 4th line and then check orderCount on the 5th, before your asynchronous call has completed. On your second click your async call has now completed and the code is doing what you think it should be doing on the first click.

You need to move your orderCount checking logic inside your anonymous 'success' callback function, so that it will only be executed when the call is complete. Or make the ajax call synchronous (jquery options)


First of all, you need to realize that setOrderCount is an asynchronous function. It will launch the ajax call and that ajax call may take awhile to process. The setOrderCount function will return right away, long before the ajax call has completed and thus long before the orderCount variable has been set.

Then, in your click handler, you immediately check the orderCount variable, but it is not set yet. What you need to do is move this code to the success function from the ajax call:

   if ( orderCount == 0 ){
        if (validateAcknowledment($(this).attr('id'))){
            acknowledgeDay($(this).attr('id'));
        }       
    }

because that's when the orderCount variable is actually set.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜