I’m trying to parse a JSON response, but any instruction in the $.getJSON cannot be executed.
The json.html
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
</head>
<body>
<script>
$.getJSON("json.php?jsoncallback=?", function(data) {
var a = data[0].cve_id + 'something';
});
alert(a); //chrome says "a is not defined"
</script>
</body>
</html>
The json.php:
<?php
header("Content-Type: application/json", true);
echo file_get_contents("http://www.cvedetails.com/json-feed.php?numrows=10&vendor_id=0&product_id=0&version_id=0&hasexp=1&opec=1&opov=1&opcsrf=1&opfileinc=1&opgpriv=1&opsqli=1&opxss=1&opdirt=1&opmemc=1&ophttprs=1&opbyp=1&opginf=1&opdos=1&orderby=1&cvssscoremin=0");
?>
Any idea why?
LATER:
Thanks for the replies. I’ve understood the reason.
I’ve switched from $.getJSON to $.get, specifying the data type to json.
var a is defined inside the callback closure (anonymous function). One of the main reasons to use closures is that they produce private scope. I.e. any variables defined inside the function will not available to code outside of the function.
This will work: