Reputation: 924
I have a web service and I'm trying to get data by JSON. if I access within the same server works fine but when I upload it to the hosting it doesn't work. the problem is the "?callback=?" param. with chrome i see the returned json but the code below didn't show it in the input text:
<html><head> <script src="jquery-1.7.1.min.js" type="text/javascript" ></script>
<script>
$(document).ready(function()
{
$("#cons").click(function(){
alert("wait");
var nombre = $("#nombre").attr('value');
if(nombre!==''){
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
$.getJSON("http://grup15.mihost.info/index.php/WS/Api/user/nombre/"+nombre+"/ano/"+ yyyy +"/mes/"+mm+"/format/json?callback=?", function(data) {
var htmlResult = "";
$.each(data, function(key, val) {
htmlResult += val.total;
});
$('#gasto').attr('value',htmlResult);
});
}else{
alert("Nombre Necesario");
}
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Nombre:</td>
<td><input type="text" id="nombre" value=""/></td>
</tr>
<tr>
<td>Gasto De este mes:</td>
<td><input id="gasto" type="text" value=""/></td>
</tr>
<tr><td colspan="2"><button id="cons" type="button">Consultar</button></td></tr>
</table>
</body>
If i delete the "?callback=? chrome shows: "not allowed by Access-Control-Allow-Origin" what i have to do??? thanks for the help!
Upvotes: 0
Views: 552
Reputation: 14225
If you can't make a JSONP you could build a wrapper function to fetch your data. Maybe via PHP.
Take a look: craigslist rss feed. My solution is build to work with XML but ist should be easily converted to work with JSON.
Upvotes: 0
Reputation: 11633
Javascript adheres to the "same origin" policy, as described here:
http://en.wikipedia.org/wiki/Same_origin_policy
This is a security measure to prevent cross-site scripting.
You might consider workarounds discussed here: Ways to circumvent the same-origin policy
Upvotes: 1
Reputation: 227310
?callback=?
means JSONP, which means the server should return JSONP, not JSON.
JSONP is actually a script, that looks like so:
func({data: 123, test: 456});
Your data needs to be wrapped in the value of the callback
parameter.
Upvotes: 2
Reputation: 114417
You cannot make AJAX requests cross-domain like this. Use JSONP instead.
Upvotes: 2