angularjs jsonp don't work localy-Collection of common programming errors
I tried out one of Angulars demo and wanted to play with jsonp. And i could not get it to work, so i pasted the same code into jsbin so i can ask you guys whats wrong with it. And notice that it worked.
Tried the exact same code again on my dev-site. and it dose not work. i can see the network log in webkit that i get a valid json back with http code 200. but no callback is executed.
I ended up trying out jQuery-Ajax on the same request and that worked fine. for me
$(document).ready(function() {
$.getJSON('http://angularjs.org/greet.php?callback=?&name=Super%20Hero', function(data) {
console.log(data); // Works
});
});
Here is a demo of my code that dosn’t work localy http://jsbin.com/ojibel/edit#html,live
EDIT: i switched from .html to .php extension and it started to work. so it have to do something with apache?
-
in JQUERY api doc its mentioned that
“However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.”
I modified your code at http://jsbin.com/ojibel/3/edit
if you see i have created a function called getData and same function i am passing as call back URL and so i am able to display it in console.
The way JSONP works is it tries to add the URL as script tags and the out put of the URL is considered as script and that code executes as it is. so if you have call back xyx in output you will have something like
xyz(DATA_FROM_SERVER)
which will be same as
xyz(DATA_FROM_SERVER)
-
When you say that it “doesn’t work”, can you describe the steps you are taking and what’s the expected vs actual result?
Please notice that in your example you are using $http with $templateCache and at the bottom of the html file there is
Hello, $http!
, which will populate the cache with a response forhttp-hello.html
requests, so if you fetch /http-hello.html, there will be no request made to the server and the callback will be called with the cached content.