Jsonp request using jquery to fetch bing web results
using this as a guide: http://msdn.microsoft.com/en-us/library/dd250846.aspx
can someone help me with the jquery call?
Do I actually pass in the javascript code for the callback, or just the name of the function?
BingSearch = function($bingUrl, $bingAppID, $keyword, $callBack) {
$bingUrl = $bingUrl + "?JsonType=callback&JsonCallback=" + $callBack + "&Appid=" + $bingAppID + "&query=" + encodeURI($keyword) + "&sources=web";
$.ajax({
dataType: 'jsonp',
jsonp: $callBack,
url: $bingUrl,
success: function(data) {
alert('success');
$callBack(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus);
}
});
};
Update
Ok so I changed this to:
BingSearch = function(bingUrl, bingAppID, keyword, callback) {
var url = bingUrl + "?method=?&JsonType=callback&Appid=" + bingAppID + "&开发者_StackOverflow中文版;query=" + encodeURI(keyword) + "&sources=web";
$.getJSON(url, callback);
};
Calling it like:
BingSearch(url, appid, searchkeyword, function(searchresults) {
alert('yes!');
};
Still getting the 'invalid label' error.
To use do jsonp with jQuery, replace the JsonCallback=UserCallback
with JsonCallback=?
. jQuery will then handle it like a regular $.ajax()
request.
I suggest starting out with $.getJSON()
to get used to the Bing API and moving back to $.ajax()
when your ready to integrate it with your application.
Using the example from the Bing API docs:
var apikey = 'YOUR_API_KEY';
var url = 'http://api.bing.net/json.aspx?AppId='+apikey+'&Version=2.2&Market=en-US&Query=testign&Sources=web+spell&Web.Count=1&JsonType=callback&JsonCallback=?';
$.getJSON(url, function(data) { console.log(data); });
jsonp:
needs to be set to a string (I think it can also be left out), as this is just the name of the dynamically created function used to receive the JSONP.
But the formal parameter $callBack needs to be a reference to a function, so either you use
function callback(result){ /*processResultHere*/ }
BingSearch(..,..,.., callback);
or
BingSearch..,..,.., function(result){ /*processResultHere*/ });
And just so you know it, the excessive use of $ really hurts my eyes :)
Also, function names beginning with a capital should be reserved for 'classes', as many syntax checkers will complain on functions with capitals being called without new
in front..
精彩评论