1

I am writing a very very simple script in html to parse json data but I am not getting the output in the browser for the div element? Iam sure I am doing a stupid thing somewhere but not getting that.

HTML,JS,JQUERY

<h1>Ajax Hellow World</h1>

    <script type="text/javascript" >
        $(document).ready(function () {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "JSON/MyList.json", true);   
            xhr.setRequestHeader("Content-type", "application/json", true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = JSON.parse(xhr.response);
                    $('#results').html(data.user);
                        }
            }
            xhr.send(null);
            $('#results').html("Working...........");
        });     
    </script>
    <div id="results"></div>

MyList.json is located in JSON Folder.

JSON File

{ "user":"John", "Age":44, "Location":"LA" }
4
  • What are you getting? Are there any console errors? Does your onreadystatechange ever get called? If it does, is the xhr.response what you actually expect it to be? Oct 24, 2014 at 13:20
  • Well for one thing, your JS and JQuery have an error. You need a semicolon after the } just above xhr.send(null);
    – MattD
    Oct 24, 2014 at 13:24
  • Failed to load resource: the server responded with a status of 404 (Not Found).Sorry at first I did not see this.
    – Naseer
    Oct 24, 2014 at 13:24
  • @khan: Look at the network tab in your browser and see exactly what the full URL it's trying to hit is. Then try that same URL directly in your browser's address bar. I suspect you aren't hitting the URL you expect. Oct 24, 2014 at 13:31

1 Answer 1

2

Your code is correct (Although as Chris Hawkes points out, you might better served using JQuery's totally awesome $.ajax() funciton).

Assuming you're using the Visual Studio debug server, your issue is that it's not configred with a static handler for the .json file type.

You need to add this to your web.config, inside the "<configuration>" tags.

<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".json" mimeType="application/JSON"/>
    </staticContent>
</system.webServer>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.