0

I'm trying to read a JSON object in from json.js into my main.js. I'm having trouble figuring out how to get the values from the external json.js file into the main.js without using jQuery. I know it's possible, but can't figure out the solution (I've been searching for hours).

Any help would be much appreciated.

7
  • you can use Ajax... there is no need to use jQuery for that Commented Sep 6, 2013 at 3:17
  • no with plain old XMLHttpRequest Commented Sep 6, 2013 at 3:23
  • Any chance you can elaborate on that? All I can seem to find is URL requests for JSON objects using Ajax. Commented Sep 6, 2013 at 3:23
  • Am I missing something? Why can't you include json.js and access the object directly? Commented Sep 6, 2013 at 3:44
  • When you say working directory are you using a web server or loading straight from the file system? Commented Sep 6, 2013 at 3:46

1 Answer 1

2

You can use plain old XMLHttpRequest

function loadJson() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var text = xmlhttp.responseText;
            var json = JSON.parse(text);
            console.log(json)
        }
    }

    xmlhttp.open("GET", "json.js?_dc" + Math.random(), false);
    xmlhttp.send();
}

loadJson();
Sign up to request clarification or add additional context in comments.

3 Comments

What is .onreadystatechange? What is that function even doing, along with "json.js?_dc" + Math.random()?
@JonBecher probably you should read about Ajax
After reading up on what you were doing with this I figured out how to use it in my application. Thank you Arun.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.