Last active
February 22, 2024 11:08
-
-
Save SelmanKahya/6973863 to your computer and use it in GitHub Desktop.
simple example of using google dictionary word lookup.
getMean() makes an ajax call to the api, then process function takes the result string and returns defination of the word as a json object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getMean(word){ | |
if(word==""|| word=="Enter a word") | |
return; | |
ajax = new XMLHttpRequest(); | |
// result callback | |
ajax.onreadystatechange = function(){ | |
if(ajax.readyState==4 && ajax.status==200){ | |
var massaged = ajax.responseText.replace(/^[^(]+\(|[^}]+$/g, ''), res; | |
try { | |
res = JSON.parse( massaged ); | |
} catch( e ) { | |
res = new Function( 'return ' + massaged )(); | |
} | |
$('#result').val(process(res)); | |
} | |
} | |
// make the call | |
var encoded = encodeURIComponent("http://www.google.com/dictionary/json?callback=process&sl=en&tl=en&restrict=pr,de&client=te&q=" + word); | |
ajax.open("GET","proxy.php?url=" + encoded,true); | |
ajax.send(null); | |
} | |
// iterates through json result object, returns word definition object | |
function process(json_obj){ | |
var result = { | |
sound : null, | |
pronunciation : null, | |
primary_means : null | |
}; | |
for (var prop in json_obj){ | |
if(prop=="primaries"){ | |
var stuff = json_obj["primaries"][0]; | |
// get pronunciation and sound | |
var isa = ""; | |
var sound; | |
var pro = stuff["terms"]; | |
for(var i=0;i<pro.length;i++){ | |
if(pro[i]["type"]=="phonetic"){ | |
isa+=pro[i]["text"]; | |
isa+=" "; | |
} | |
else if(pro[i]["type"]=="sound"){ | |
sound = pro[i]["text"]; | |
} | |
} | |
result.sound = sound; | |
result.pronunciation = isa; | |
// get meaning array | |
var primary_mean = stuff["entries"]; | |
var primary_mean_list = []; | |
var k=0; | |
for(var i=0;i<primary_mean.length;i++){ | |
if(primary_mean[i]["type"]=="meaning"){ | |
primary_mean_list[k]=primary_mean[i]["terms"][0]["text"]; | |
k++; | |
} | |
} | |
result.primary_means = primary_mean_list; | |
} | |
else | |
continue; | |
} | |
return result; | |
} | |
var result = getMean('Philodendron'); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment