Reputation: 15548
I want to read the JSONP data from an external domain in raw JavaScript (no jQuery).
So let's say https://www.domain.com/abc.php?foo=bar
contains: {"error":false,"data_a":"abcabc","data_b":"123-456"}
I couldn't really find much about this on google. But if I understood it correctly it should work about like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://www.domain.com/abc.php?foo=bar&callback=DataCallback";
</script>
</head>
<body>
<script>
function DataCallback(data) {
for (var key in data) {
var value = data[key];
alert(key+' = '+value);
}
}
</script>
</body>
</html>
I don't get an error, but I also don't get any alerts popping up.
Btw, I noticed that
https://www.domain.com/abc.php?foo=bar
and
https://www.domain.com/abc.php?foo=bar&callback=DataCallback
both show {"error":false,"data_a":"abcabc","data_b":"123-456"}
in the browser.
Could that be the problem? Because I thought that the second link should show:
DataCallback({"error":false,"data_a":"abcabc","data_b":"123-456"})
?
Upvotes: 0
Views: 730
Reputation: 31
I have complete pure javascript jsonp example...
You can have a look if you want
https://github.com/toosha01/ajax-javascript
Upvotes: 0
Reputation: 944320
You have two problems.
You are never sending the request
You have to add the script element to the document before it will be executed.
document.body.appendChild(script);
(Don't try doing that before the body exists or before you have defined your callback function)
The server is not responding with JSONP
You can't process plain JSON as if it were JSONP. The server is responding with JSON (well, when I try it, it responds with an advert for buying domains … perhaps you meant example.com
?)
Upvotes: 2