write a parsed response from a json file in a div

167 views Asked by At

let's say that I have a json file like this: http://www.example.com/json?jsonp=parseRespond

My HTML code:

<script src="http://www.example.com/json?jsonp=parseRespond"></script>

http://www.example.com/json?jsonp=parseRespond respond is:

{"id":"5572a7d648b33a462d79145d","avatarHash":null,"bio":"","bioData":null,"confirmed":false,"fullName":"Ender Widgin","idPremOrgsAdmin":[],"initials":"EW","memberType":"normal"}

How can I get the parsed respond header ? Here is what I have tried so far:

 var _request = undefined;
 var headers = _request.getResponseHeaders();
 document.write(headers);

But , it doesn't work!

Note: I am not doing XMLHttpRequest because Origin is not allowed by Access-Control-Allow-Origin.

Note: I am not using callback=apiStatus as it redirects to an unauthorized link.

so the only way I can get response is when using jsonp=parseRespond , how can I write that response in a div ?

1

There are 1 answers

1
TaoPR On

Since you're using JSONP to handle the data received from the server, you need to write your own function parseRespond which takes that data as an argument and, perhaps, print it to the particular DIV you want.

Given the URL:

http://www.example.com/s.json?jsonp=parseRespond

You'll need to write a function entitled parseRespond like follows

function parseRespond(data){
    // data is the response you received from that URL
    // e.g. data = {
    //     name: "John", 
    //     surname: "Conor",
    //     titles: ["Resistance Leader","Survivor"]
    // }

    // encapsulate, format or do something with the data here
    var output = data.name + " " + data.surname + " as " + data.titles.join(",");

    // Then print the output to your DIV like this example:
    $("#mydiv").html(output);
}

NOTE: JSONP is a JSON with callback, the term you specify in jsonp=func leads to a function callback pointing to func. Further information you may want to read is well organized and discussed in this thread:

What is JSONP all about?