Domanda

I cant seem to get this for the life of me. I cant access the variable "json" after I calll the getJson2 function. I get my json dynamically through a php script, and that works. But then its gone. there is a sample that I use as a guide at The InfoVis examples where the json is embedded in the init function. i am trying to get it there dynamically.

<script language="javascript" type="text/javascript">
var labelType, useGradients, nativeTextSupport,animate,json;
function getJson2()
{
  var cd = getParameterByName("code");
  $.get("tasks.php?code="+cd, function(data){
    return data;
  })
 };
function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

(function() {
  var ua = navigator.userAgent,
      iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
      typeOfCanvas = typeof HTMLCanvasElement,
      nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
      textSupport = nativeCanvasSupport 
        && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
  //I'm setting this based on the fact that ExCanvas provides text support for IE
  //and that as of today iPhone/iPad current text support is lame
  labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
  nativeTextSupport = labelType == 'Native';
  useGradients = nativeCanvasSupport;
  animate = !(iStuff || !nativeCanvasSupport);
})();
debugger;
var Log = {
  elem: false,
  write: function(text){
    if (!this.elem) 
      this.elem = document.getElementById('log');
    this.elem.innerHTML = text;
    debugger;
    this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
  }
};  
function init(){
json = getJson2();
    //init data
var st = new $jit.ST({  
    //id of viz container element  
    injectInto: 'infovis',  
    //set duration for the animation  
    duration: 800,  
    //set animation transition type  ..................
È stato utile?

Soluzione

function getJson2()
{
  var cd = getParameterByName("code");
  $.get("tasks.php?code="+cd, function(data){
    return data;
  })
};

getJson2() doesn't return anything. The callback function to $.get() returns something, but nothing is listening for that return.

It sounds like you want synchronous loading instead. $.get() is just shorthand for this $.ajax() call: (See docs)

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

And $.ajax() supports more features, like setting async to false.

$.ajax({
  url: "tasks.php?code="+cd,
  async: false,
  dataType: 'json',
  success: function(data) {
    // data !
  }
});

Which means, getJson2 then becomes:

function getJson2()
{
  var cd = getParameterByName("code");
  var jsonData;

  $.ajax({
    url: "tasks.php?code="+cd,
    async: false,
    dataType: 'json',
    success: function(data) {
      jsonData = data;
    }
  });

  return jsonData;
};

var myJsonData = getJson2();

Or still use $.get async style, and use callbacks instead.

function getJson2(callback)
{
  var cd = getParameterByName("code");
  $.get("tasks.php?code="+cd, function(data){
    callback(data);
  });
};

getJson2(function(data) {
  // do stuff now that json data is loaded and ready
});

Altri suggerimenti

The $.get call is asynchronous. By the time you call return data;, the function has already long since returned. Create a variable outside of your function's scope, then in the $.get callback handler, assign data to that variable.

var json;

function getJson2(){
    // ...
    $.get(...., function(response){
        json = response;
    }
});

Alternatively, you could do a sychronous Ajax call, in which case returning your data would work (but of course would block script execution until the response was recieved). To accomplish this, see the asynch argument to jQuerys $.ajax function.

A jQuery $.get call is asynchronous and actually returns a promise, not the data itself.

An elegant way to deal with this is to use the then() method:

$.get(...).then(function(data){...});

Alternately, change your ajax settings to make the call synchronous.

$.get("tasks.php?code="+cd, function(data){
    return data;
  })

$.get is asynchroneous. So your value is never returned. You would have to create a callback.

The same question appears here: Return $.get data in a function using jQuery

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top