开发者

javascript - set var equal to data returned from a function

var ipAddress="unknown";
$.getJSON('http://jsonip.appspot.com/?callback=?',
function(data){
ipAddress=data.ip;});


document.getElementById('callbackForm').elements["callback_form.ipAddress"].value = ipAddress;

This javascript code sets the var ipAddress equal to 'unknown', then executes a jquery function that sets the value of ipAddress to the user's ip. Then I attempt to set a form element equal开发者_Go百科 to the value of ipAddress.

This is not working. The form element is being set to 'unknown'. I'm not sure if this is a scoping problem? Any advice appreciated.


What's happening is that the callback is executing asynchronously. The $.getJSON call tells the browser "go off and get data from this URL; when it's ready, call the function I've provided". That function doesn't execute right away.

You can either move more logic into the callback (i.e. inline the ipAddress var and assign to your form element in the callback), or switch to the more full-featured jQuery.ajax method and pass async:false in the option set. Of course, in all cases you'll be waiting for the network before the rest of the call executes.


Asynchronous JavaScript and XML (ajax) is asynchronous (even if it doesn't involve XML).

The callback function executes when the HTTP response arrives.

The rest of the code just runs immediately — i.e. before the response has arrived.

If you want to do anything with the requested data do it inside the callback

var ipAddress="unknown";
$.getJSON('http://jsonip.appspot.com/?callback=?',function(data){
    ipAddress=data.ip;
    document.getElementById('callbackForm').elements["callback_form.ipAddress"].value = ipAddress;
});


This is how it should be reworked:

$.getJSON('http://jsonip.appspot.com/?callback=?', function(data){
    setIPAddress(data.ip);
});

function setIPAddress(ip){
  document.getElementById('callbackForm').elements["callback_form.ipAddress"].value = ip;
}


Put the code that sets the value inside the callback.


This line:

document.getElementById('callbackForm').elements["callback_form.ipAddress"].value = ipAddress;

is executing before ipAddress gets set with the correct value. Try moving the line into the callback method.


maybe you have asynchronous issues.

why you don't modify the element inside the json callback function?


$.getJSON is just a short-cut way of using $.ajax. So it's asynchronous. Use the document.getElementById('callbackForm')... inside the jSON callback.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜