I’m trying to use the Jquery UI Autocomplete to retrieve synonyms for any word using a Thesaurus API.
I need to make a following json GET request to access the API
http://words.bighugelabs.com/api/{version}/{api key}/{word}/{format}
Jquery however generates the following which returns a 404 Not Found
http://words.bighugelabs.com/api/?v=2&key=mykey&word=some-word&format=json
Is it possible to easily remove the separators?
Script
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#thesaurus" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://words.bighugelabs.com/api/",
dataType: "json",
data: {
v: "2",
key: "mykey", //actually numbers
word: request.term,
format: "json"
//maxRows: 12,
//name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.noun ? ", " + item.noun : "") + ", " + item.syn,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
HTML
<input id="thesaurus" />
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
The whole point of the data parameter to the
$.ajax()function is to create a query string (both POST and GET use query strings, they are just sent as different parts of the request payload). You just want to use simple string concatenation to build your URL.You had static version, api key and format parameters but if they were dynamic, the url would look like:
To make your code a little cleaner you could even go as far as: