類定義html
/** 前端 * Google翻譯的ajax接口簡單封裝ajax */函數 class GoogleTranslateAjaxAPI {測試
* 調用Google翻譯ajax接口,直接返回編碼 */url public static function translate($content, $fromLang = 'zh-CN', $toLang = 'en', $fromEnc = 'UTF-8', $toEnc = 'UTF-8') {spa try {翻譯 // 由於是經過URL傳遞參數,須要編碼,還可能存在長度限制 $content = trim($content); $content = urlencode($content); $url = "http://translate.google.cn/translate_a/t?client=t&sl=$fromLang&tl=$toLang&hl=en&sc=2&ie=$fromEnc&oe=$toEnc&oc=1&otf=2&srcrom=1&ssel=5&tsel=5&q=$content"; $html = file_get_contents($url); } catch (Exception $ex) { $html = ''; } return $html; } } |
使用示例
/** * 獲取客戶端提交數據 */ function getRequest($key, $default = null) { return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default; }
/** * 頁面入口函數 */ function main() { header("Content-type: text/html; charset=utf-8"); $fromLang = getRequest('fromLang', 'zh-CN'); $toLang = getRequest('toLang', 'en'); $fromEnc = getRequest('fromEnc', 'UTF-8'); $toEnc = getRequest('toEnc', 'UTF-8'); $content = getRequest('content', '測試'); $googleret = GoogleTranslateAjaxAPI::translate($content, $fromLang, $toLang, $fromEnc, $toEnc); return $googleret; }
echo main(); |
前端JS
$.get(url, {toLang: toLang, content: inputContent}, function(data){ // 因爲調用了Google翻譯的ajax接口,此處data格式爲Google定義格式 var data = new Function("return " + data)(); var sentences = [], i = 0, len = data[0].length; // 合併每個句子中的目標翻譯對象 for(i = 0, len = data[0].length; i<len; i++) { sentences.push(data[0][i][0]); } // 替換到文本輸入框中 $('#output').val(sentences.join(' ')); }, 'text');