0

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"})
?

2 Answers 2

2

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?)

Sign up to request clarification or add additional context in comments.

Comments

0

I have complete pure javascript jsonp example...

You can have a look if you want

https://github.com/toosha01/ajax-javascript

1 Comment

Please add this as comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.