I know this has been asked a zillion times, but I still can't get my code to work. I am trying to a simple JSONP call from my Javascript application. The cod fragment looks like:
url="http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=?";
and then either:
$.getJSON(url, function(data) {
alert('hello 1');
});
or:
$.ajax({url: url,
datatype: 'jsonp',
success: function(data) { alert("hello 2"); },
error: function(j, t, e) { alert(t);}
});
Neither approach works. The second approach results in the alert of "error". The first does not return success either. What am I doing wrong? Many, many thanks!!
UPDATE: I think I found at least one problem. Let me look more into this.
UPDATE 2: Sorry, this code actually works, at least the first approach. There was a subtle error around this code fragment that resulted in the code not working, but overall this works just fine. Asynchronous calls are sometimes a little tricky :-)
Check this out JsFIddleDemo
/*
* create callbak function for jsonP
* @params
* data is response from http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=myjsonpfunction
*/
function myjsonpfunction(data){
alert(data.responseData.results) //showing results data
$.each(data.responseData.results,function(i,rows){
alert(rows.url); //showing results url
});
}
//request data using jsonP
$(function(){
$.ajax({
url:'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=myjsonpfunction',
type:"GET",
dataType: 'jsonp',
jsonp: 'myjsonpfunction',
async:'true',
success:function (data) {
//alert("success");
}
});
});
you need write a callback parameter and callback function,the google ajax apis will be return only json if you don't set of callback.
if you set url like this
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=?(another)
the response is
{"responseData": null, "responseDetails": "bad or missing callback or context", "responseStatus": 400}
Looks like the method you are using is deprecated: https://developers.google.com/web-search/docs/reference
And has moved on to: http://code.google.com/apis/customsearch/v1/overview.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With