Link to home
Create AccountLog in
Avatar of Alan Varga
Alan VargaFlag for United States of America

asked on

How to save JSON file data to a string outside of jQuery.getJson

This is a follow-up to a scenario I posted last week.  How do I retrieve the value "livingroom" from a json text file into a javascript string variable that can be used throughout the script?  My reading to date has told me to avoid the JSON eval method, but all script examples of JSON.parse use text defined with  the script.  I have also run across jquery.json-2.3.js, but since I'm a beginner, I have no idea how to use any of its methods.

file: computerid.json
{"computer":
    {"id": "livingroom"}
}

Open in new window


file: foobar.html
<!DOCTYPE html>
<html lang="en">

<head>
  <title>JSON Example</title>
  <script type="text/javascript"
          src="foobar.js"></script>
  <script type="text/javascript"
          src="jquery-1.7.min.js"></script>
</head>
<body onload="showComputerName();">
</body>
</html>

Open in new window


file: foobar.js
function getComputerName () {
    jQuery.getJSON('computerid.json', function(obj) {
        var sResult = obj.computer.id;
	});
}

function showComputerName() {
    var sComputerId = getComputerName();
    alert("This script is running on the computer named " + sComputerId);
    if(sComputerId = "livingroom") {
        alert("Your operating system is Windows XP");
    }
}

Open in new window


ASKER CERTIFIED SOLUTION
Avatar of webtronick
webtronick
Flag of Belgium image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Alan Varga

ASKER

Thanks, that looks like a step in the right direction.  What I'm after, though, is to not make one script dependent on the other.  I want to save sComputerId so that it is available to any other function or script in my HTML page, so that I don't have to refer back to the initializing function once the page is loaded.  Can I declare sComputerId outside the functions but assign it with getComputerName()?  Maybe in a body onload event?

By the way, thanks also for catching my oversight on the "if" comparison.  I was just sloppy and in a hurry; you're right, I need a double equal sign.
I would have liked an answer to my follow-up question, but I now have enough knowledge to move forward.