Here is the way I test JSONP: I run XAMPP, and in folder htdocs I create a javascript folder . I create json1.json file contain some data to process.
After that, I run this html file locally, and it will call a function in “other machine” (in this case is localhost)
Here is my code in this problem :
<head>
<script>
function updateSales(sales) {
alert('test jsonp');
// real code here
}
</script>
</head>
<body>
<h1>JSONP Example</h1>
<script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>
</body>
But when I run, nothing happen. But if change to other real json on the internet, it will work. It means change line :
<script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script>
to line:
<script src="http://gumball.wickedlysmart.com/?callback=updateSales"></script>
It will work smoothly.
So, I don’t know how to test JSONP by using localhost, please help me.
Thanks 🙂
JSONP is generated on the server’s side. The server fetches your data, encodes it as JSON and then wrap a function call around it.
So in your case you can either modify your
.jsonfile the following way:This, however, would have a hardcoded call back method, so it wont react on changes you do at retrieving it.
The other way is to write a small PHP wrapper (or use whatever else you like) and add the function around the JSON, before sending it back to the client.
(The later code is by no means for any productive use, but only for local testing!)