2010-12-06 48 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,将在同一范围