Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I struggled a lot with this problem, so hopefully this will help someone in the future :)</p> <p>JSONP expects a function callback, a common mistake is to call a URL that returns JSON and you get a <em>Uncaught SyntaxError: Unexpected token :</em> error. Instead, JSONP should return something like this (don't get hung up on the function name in the example):</p> <pre><code>angular.callbacks._0({"id":4,"name":"Joe"}) </code></pre> <p>The <a href="http://docs.angularjs.org/api/ng.%24http#jsonp">documentation</a> tells you to pass JSON_CALLBACK on the URL for a reason. That will get replaced with the callback function name to handle the return. Each JSONP request is assigned a callback function, so if you do multiple requests they may be handled by angular.callbacks._1, angular.callbacks._2 and so forth.</p> <p>With that in mind, your request should be something like this:</p> <pre><code>var url = 'http://myserver.com:8888/dosomething/me@mydomain.com/arg2'; $http.jsonp(url + '?callback=JSON_CALLBACK') .then(function (response) { $scope.mydata = response.data; ... </code></pre> <p>Then AngularJS will actually request (replacing JSON_CALLBACK): </p> <pre><code>http://myserver.com:8888/dosomething/me@mydomain.com/arg2?callback=angular.callbacks._0 </code></pre> <p>Some frameworks have support for JSONP, but if your api doesn't do it automatically, you can get the callback name from the querystring to encapsulate the json. Example is in Node.js:</p> <pre><code>var request = require('request'); var express = require('express'); var app = express(); app.get('/', function(req, res){ // do something to get the json var json = '{"id":4,"name":"Joe"}'; res.writeHead(200, {"Content-Type": "application/javascript"}); res.write(req.query.callback + '(' + json + ')'); res.end(); }); app.listen(8888); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload