2012-08-22 21 views
-1

對象窗口上的設置,如果我在警報下調用函數[ctrUpadateCount],只會得到「固定」,如果我直接調用它不會工作。 任何想法爲什麼?我在另一個項目上遇到同樣的問題。並且必須得到一個解決方案,這是可以應用在這裏的。 我試着解釋下面的代碼... ps:對不起英文不好。Ajax設置全局變量,但超出價值desapear

function ctrUpdateCount(idCtrForm) 
{  
    $.ajaxSetup({ assync: false}); 
    tableName= 'clients'; 
    p_comando="select count(*) total from "+tableName; 
    $.post("execute.php", {comando : p_comando}, function(json){   
    v_total=json[1].total ; // <= this retuns 3 
    window['ctrBuffer_'+idCtrForm].count=v_total; 
    alert("count inside = "+ window['ctrBuffer_'+idCtrForm].count);//this alerts 3 
    },'json'); 
} 

jQuery.fn.extend({ ctrLoad: function() 
    { 
    if($(this).get(0).tagName =='FORM'){  
    idCtrForm=$(this).attr('id'); 
    alert("direct count ="+ctrUpdateCount(idCtrForm)); // this will alert 3 
                 // and so the next alert 
    //teste=ctrUpdateCount(idCtrForm); // but if i use this, 
             //the next alert will show "undefined" 
    alert("count after = "+ window['ctrBuffer_'+idCtrForm].count); 
    } 
    } 
}) 
+0

哦,你是通過Ajax發送原始SQL嗎?小鮑比桌子會很興奮。 –

+0

好悲痛,這只是一遍又一遍地被問到。 – Pointy

回答

1

你 「ctrUpdateCount」 功能使用$.post(),這是異步。該函數不可能返回由該異步操作的結果確定的值;這本質上是無意義的。

我真的不能告訴你想要做什麼,但基本上你必須做你需要的「POST」操作的結果裏面做回調函數,以$.post()什麼。

+0

好吧,這段代碼並不像安全,但我主要的疑惑是爲什麼這個窗口['anything']。count,函數內部返回一個值而不是外部? – Fernandof

+0

'$ .post()'調用立即返回,但瀏覽器完成HTTP請求需要時間。您傳遞給'$ .post()'的函數將不會**立即運行 - 它會在HTTP請求完成時運行。 – Pointy