Reputation: 1155
<html>
<head>
<title>Group Test</title>
<script type="text/javascript" src="/static/javascript/jquery-1.8.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
var global = new Array();
$.ajax({
url: "/json",
success: function(reports){
global = reports;
process(reports);
return global;
}
});
function process(reports){
for (i=0; i<reports.length; i++) {
document.write(i + " : "+reports[i].fields.report_name+"<br>");
}
}
</script>
</body>
</html>
OK, so there is my code. I am trying to use the JSON data throughout my code, but for some reason, I get a "reports is undefined" error whenever I try to use the reports object outside of the $.ajax() function.
According to JSLint, the code looks good, AND lists both the reports and the variable global as global variables.
If I try to run anything that uses either of those outside, it won't work.
'success'(reports)
global
global
line 22
process(reports)
global
document
Upvotes: 0
Views: 2078
Reputation: 99234
Keep in mind $.ajax
is async, so unless you call your functions inside the success callback, the value might not be set yet.
Also you'd need to use global
not reports
.
Upvotes: 0
Reputation: 23208
You can not access reports
as global object only global
can be accessed from every place. reports
is a local variable to success as well as for process
function
<script type="text/javascript">
var global = new Array();
$.ajax({
url: "/json",
success: function(reports){
global = reports;
process(reports);
return global;
}
});
function process(reports){
for (i=0; i<reports.length; i++) {
document.write(i + " : "+reports[i].fields.report_name+"<br>");
}
}
// reports is undefined here. but global can be accessed (will be empty array before success function get called)
</script>
Upvotes: 1