1

I'm making a jsonp request and I get this error Refused to execute script from 'https://myurl/test.php?callback=%27callback%27' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. despite the request returns a 200 code.

function callback(response){
    alert(response);
}

var script = document.createElement("script");
//Set the Type.
script.type = "text/javascript";
//Set the source to the URL the JSON Service.
script.src = "https://myurl/test.php?callback='callback'";
//Append the script element to the HEAD section.
document.getElementsByTagName("head")[0].appendChild(script);

and this is test.php

<?php
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

    echo json_encode($arr);
?>
af_inb
  • 103
  • 1
  • 6

2 Answers2

0

In PHP, set before the echo

header('Content-Type: application/json');

And your PHP doesn't have any callback (you're not returning JSONP). You want it to look something like..

echo $_GET['callback'].'('.json_encode($arr).')';

Edited

I missed the absolute obvious. JSONP is for cross site AJAX calls. You're using it as a script.

This is a very awkward way to load data. The normal way is to load the data through an AJAX call within a script, not load variables globally.

If you really want to go with your design, keep the application/json tag but go back to your original echo json_encode($arr); You can also drop the ?callback='callback' -- it does nothing.

D. Walsh
  • 1,963
  • 1
  • 21
  • 23
  • Now says that callback is not a function – af_inb Jan 12 '17 at 15:33
  • @af_inb I updated the answer. – D. Walsh Jan 12 '17 at 15:38
  • with `echo json_encode($arr);` Iget this error `Uncaught SyntaxError: Unexpected token :` on `{"a":1,"b":2,"c":3,"d":4,"e":5}` – af_inb Jan 12 '17 at 15:44
  • That's because your data is simply floating in space. Again, your implementation is very non standard and you should refactor your code. You'd have to, essentially, write Javascript in your PHP code. Try echo "const variable = ".json_encode($arr); – D. Walsh Jan 12 '17 at 15:48
0

you need to force specify output type. Try to add

header('Content-Type: application/json');

before output the array in test.php

and then you need to wrap entire encoded output to a callback name so js on a client-side can work with it:

$callbackName = filter_input(INPUT_GET, 'callback');
echo $callbackName . '(' . json_encode($arr) . ')';
Panama Prophet
  • 1,027
  • 6
  • 6