【发布时间】:2014-07-14 22:24:02
【问题描述】:
我正在尝试用谷歌翻译翻译文本:
$.ajax({
type : "GET",
url : "https://www.googleapis.com/language/translate/v2",
dataType : 'jsonp',
cache : false,
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
data : "key="+translateKey+"&source=en&target=de&q=Hello",
success : function(res) {
console.log('res', res.data.translations[0].translatedText);
},
error : function(xhr, ajaxOptions, thrownError) {
}
});
$.get("https://www.googleapis.com/language/translate/v2", {
key : translateKey,
source : "en",
target : "fr",
q : "hello"
}, function(res) {
console.log(res.data.translations[0].translatedText);
}, "json").fail(function(jqXHR, textStatus, errorThrown) {
alert("error :" + errorThrown);
});
我正在使用 API:
- Google+ API
- Google+ 域 API
- 翻译 API
我创建了一个 Google 项目并插入了我的本地主机和我的真实站点地址。 我返回了一个错误 403 禁止。
我尝试将它复制到这样的 URL 中: https://www.googleapis.com/language/translate/v2?key=AIzaSyCClt5fo3FDMAym59FQw-R5D39eaTNfWIg&source=en&target=de&q=Hello
我收到错误 JSON。 我哪里错了?
我正在使用 AJAX 和 Javascript 编写代码。
答案在这里!!!
您必须付费。但如果有人想使用,它们是 php 中的黑客:
<?php
function curl($url,$params = array(),$is_coockie_set = false){
if(!$is_coockie_set){
/* STEP 1. let’s create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
}
$str = ''; $str_arr= array();
foreach($params as $key => $value){
$str_arr[] = urlencode($key)."=".urlencode($value);
}
if(!empty($str_arr))
$str = '?'.implode('&',$str_arr);
/* STEP 3. visit cookiepage.php */
$Url = $url.$str;
$ch = curl_init ($Url);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
return $output;
}
function Translate($phrase, $from , $to){
$ret = "";
if(strlen($phrase)>1600){ //split and translate each part individually to get around 2048 size limit:
$phrases = str_split($phrase,1600);
foreach($phrases as $p) $ret .= translate($p, $from, $to);
return($ret);
}else{
$url = "http://translate.google.com/translate_a/t?client=p&q=".urlencode($phrase)."&hl={$to}&sl={$from}&tl={$to}&ie=UTF-8&oe=UTF-8&multires=0" ; // client = p !
$out = json_decode(curl($url), 1);
foreach($out['sentences'] as $sentence){
$ret .= $sentence['trans'].' ';
}
return stripslashes(trim($ret));
}}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body dir="rtl">
<?php
$text = "my name is name" ;
echo Translate($text,'en','iw');
?>
</body>
</html>
【问题讨论】:
-
“未配置访问权限。请使用 Google Developers Console 为您的项目激活 API。”
-
如果您的意思是激活 api 并获取生成密钥,我已经这样做了
标签: javascript jquery ajax html google-translate