Z
Z
ZaxapKramer2016-06-24 19:19:40
JavaScript
ZaxapKramer, 2016-06-24 19:19:40

How to get value from proposed JSONP with pure JavaScript?

Hello. I have been doing such things for a relatively long time - extracting data from jsonp. And at the moment I'm tempted to take javascript (without jquery and other things).

Here, in fact, is our hero - JSONP in person:

response({
  "files": [
    {
      "type": "js",
      "name": "script"
    },
    {
      "type": "html",
      "name": "file"
    }
  ]
});


And here, in fact, this is how I tried to get type:
// ...
function ajax(url, callback, parse) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = function(){
    if (this.readyState == 4) {
      if (xhr.status >= 200 && xhr.status < 400) {
        callback(parse ? JSON.parse(xhr.responseText) : xhr.responseText);
      }
    }
  };
  xhr.send(null);
}

ajax(jsonp_url, function(data) {
  data.files.forEach(function(item, i){
    alert(data.item.type);
  });
});
// ...


Before that, there were still attempts, but I stopped at forEach ... but this forEach still does not want to work. The main problem is with extracting type , not with forEach.

PS Jquery, please do not offer.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
ZaxapKramer, 2016-06-25
@ZaxapKramer

Solved the problem.
Got rid of callback - got just JSON (without "P").
Then I applied JSON.parse() to this same JSON (in my ajax function I specified true as the last parameter), I got the value through the forEach described in the question. Good luck:)

R
Rou1997, 2016-06-24
@Rou1997

It's not JSON, it's JSONP. JSON looks like this:

{
  "files": [
    {
      "type": "js",
      "name": "script"
    },
    {
      "type": "html",
      "name": "file"
    }
  ]
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question