2010-12-06 42 views
0
var = msg 
$.get('json-signup-erros.php',{},function(data){msg=data},'json'); 

function focushint() 
{ 
    alert (msg) // this works 
} 
$("input").focus(focus); 

alert(msg) //this doesnot work 

任何人都可以高我嗎?無法訪問變種外jquery

回答

8

您正在發出一個異步的AJAX請求。

msg只有在請求完成後纔會包含該值。

您應該將使用msg的代碼放入Ajax請求的success回調(function(data))中。

(有理論上的可能性,使使用async: false請求同步,但不是很好的做法,只有當它是不可避免的,應使用)

+0

我whant能夠得到錯誤味精,然後啓動JavaScript的外面,我該怎麼辦那? – dvdx 2010-12-06 11:36:35

+0

@dvdx只需將您想要啓動的Javascript放入成功回調中即可。 – 2010-12-06 11:37:09

0

我佩卡同意 - 你需要考慮的是這樣的:

var = msg; 

$.get('json-signup-erros.php',{}, function(data, response) 
{ 
    if(response == "success") 
    { 
     msg = data; 
     alert(msg); 
    } 
    else 
    { 
     alert("Whoops something went wrong, please try again."); 
    } 
},'json'); 

function focushint() 
{ 
    alert (msg); // this works 
} 

$("input").focus(focushint); 

NB。我在$ .get中添加了一個「成功」檢查...我一直都在看這個 - 你不應該假設你的Ajax Http Request會返回200響應!即如果沒有數據獲取由於錯誤而返回(404,500,401),則不能提醒它,並且您可能要通過添加else子句來警告用戶出現問題。

0
var = msg; 

$.get('json-signup-erros.php',{}, function(data, response) 
{ 
    if(response == "success") 
    { 
     msg = data; 
     alert(msg); 
    } 
    else 
    { 
     alert("Whoops something went wrong, please try again."); 
    } 
},'json'); 

function focushint() 
{ 
    alert (msg); // this works 
} 

$("input").focus(focushint); 
alert(msg); // this is still does not work 

如果您要訪問的味精jQuery函數一樣focushin,將在同一範圍