Search code examples
jqueryjsonhtmlheaderaccess-control

Bizarre issue with JSON retrieval from different domain name (headers Access-Control-Allow-Origin in place and working)


I'm trying to create a basic test with JSON grabs cross domain....I have Access-Control-Allow-Origin in place and being recognized by the browsers, and even the JSON outputting, but for whatever reason, Jquery wont utilize the content. No console errors, checked the network return and everything is fine...not sure what is going on.

Here is my html code:

<head>
  <title>Hello jQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $.ajax({
        url: "http://myurlremoved:)"
      }).then(function(data) {
        $('.greeting-id').append(data.id);
        $('.greeting-content').append(data.content);
      });
    });
  </script>
</head>

<body>
  <div>
    <p class="greeting-id">The ID is </p>
    <p class="greeting-content">The content is </p>
  </div>

From there, I'm merely outputting simple static JSON via a fake endpoint:

{"id":439,"content":"Hello, World!"} 

I've been back and forth and around on this...I'm not sure what the deal is. Anyone see anything obvious that I'm missing? The browser shows that the header is allowing the cross domain via the domain wildcard in the cross domain header...I'm not sure what else could be wrong...but this is new to me.


Solution

  • The returned result a string of a json object, not an actual object. What you'll have to do is one of the following:

    1. $.getJSON method instead of ajax.
    2. Use parseJSON on the data variable.
    3. Add dataType: "json" as one of the options below url in the ajax request.

    Try

    <!DOCTYPE html>
    <html>
        <head>
            <title>Hello jQuery</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
          <script>
    $(document).ready(function() {
        $.ajax({
            url: "http://framework.testlocker.net/endpoints/testrest.cfm",
            dataType:"json"
        }).then(function(data) {
           $('.greeting-id').append(data.id);
           $('.greeting-content').append(data.content);
        });
    });
    </script>
        </head>
        <body>
            <div>
                <p class="greeting-id">The ID is </p>
                <p class="greeting-content">The content is </p>
            </div>
        </body>
    </html>
    

    Output:

    enter image description here