Z
Z
ZaxapKramer2016-10-30 09:04:31
JavaScript
ZaxapKramer, 2016-10-30 09:04:31

Problem when getting JSON from another site using script tag, how to solve correctly?

Loading JSON with javascript like this:

var script = document.createElement('script');
script.src = json_src;
document.body.appendChild(script);
script.onload = function() {
  alert("Done!");
  console.log(JSON.parse(script).innerHTML);
}

Everything would be fine, but there are 2 problems that still cannot be solved for many hours of searching, trial and error.
  1. JSON.parse(...) doesn't want to execute. In my opinion, this is not what is needed in this case, but I did not find anything else ...
    The goal is to take the contents of the JSON received through the script, but how to do it right? Is that possible?
  2. Google Chrome throws an error: " Refused to execute script from ' *json_url* ' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled. ".
    Good. I add
    script.type = "application/json";
    as a result the following code is obtained :
    var script  = document.createElement('script');
    script.type = "application/json";
    script.src  = json_src;
    document.body.appendChild(script);
    script.onload = function() {
      alert("Done!");
      console.log(JSON.parse(script).innerHTML);
    }

    But in this case, neither Chrome nor Firefox loads anything: the tag is there, it's no use.

Many thanks in advance for your help. I'm already at a loss...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton fon Faust, 2016-10-30
@ZaxapKramer

Calling JSON.parse(str) will turn a string of JSON data into a JavaScript object/array/value.
What are you doing? You are passing in JSON.parse the object created by document.createElement('script');
Replace
JSON.parse(script).innerHTML
with
JSON.parse(script.innerHTML) Do you
understand why?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question