开发者

cant access var outside jquery

开发者 https://www.devze.com 2023-01-28 09:05 出处:网络
var = msg $.get(\'json-signup-erros.php\',{},开发者_开发问答function(data){msg=data},\'json\');
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

can anyone tall me way??


You are making an AJAX request which is asynchronous.

msg will contain the value only after the request has been made.

You should put the code that uses msg into the Ajax request's success callback (the function(data)).

(There is the theoretical possibility to make the request synchronous using async: false but that is not good practice and should be used only if it's unavoidable.)


I agree with Pekka - you need to consider something like this:

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. I put a "success" check in the $.get... I see this all the time - you should not assume that your Ajax Http Request is going to return a 200 response! i.e. if no data get's returned due to an error (404, 500, 401) you can't alert it and you may want to warn the user that something went wrong by adding an else clause.


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

If you want to access the msg outside a jQuery function like focushin that will be in the same scope

0

精彩评论

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