简体   繁体   中英

Use of global variable with ajax

Currently I am working on a website which uses asp.net and c#. I am getting data from the database using a web service and I get the correct data without an issue. However once I get the data via ajax call I need to assign it to a global variable which I later use to create a tree graph. This is where my problem comes, I've tried to assign the JSON object but I can't seem to get it to work. I keep getting an error

TypeError: treeData is undefined

Can someone guide me please. Below is the relevant code

Ajax Call

$(function () {
   $.ajax({
   type: "POST",
   url: "MyService.asmx/SomeFunction",
   data: "{}",
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: successHandler
   });
});

SuccessHandler

function successHandler(data) {
  var a = JSON.parse(data.d);
  var b = [JSON.stringify(a)];
}

var treeData = successHandler[0]; //This part keeps giving me error

Thanks in advance for all your help and support.

You are trying to access successHandler as an array, when it is a function. You cannot use it like that. Instead, assign the [JSON.stringify(a)] to a global variable, and access that variable when you need the data, like so:

var dataFromAjax; 
var treeData; 

function successHandler(data) {
    var a = JSON.parse(data.d);
    dataFromAjax = [JSON.stringify(a)];

    setTreeData();
}

function setTreeData() { //this function can be in the seperate script tag
    treeData = dataFromAjax[0]; 
}

In this case you need to return the object from the function and use it like this successHandler()[0];

 function successHandler(data) { var a = JSON.parse('[{"a":1, "b":2}]'); return a; // you need to return the data from here. } var treeData = successHandler()[0]; //This part keeps giving me error console.log(treeData) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM