我是初学者,所以没有多少经验。 任务是翻译用户编写的文本块。 所以html文件:
<script type="text/javascript">
$('#some_id').on('click', function(){
var text_var = JSON.stringify("{$text_without_adv}");
var own_script = 'gTApi.php';
$.ajax({
method: 'post',
url: own_script,
data: $.parseJSON(text_var)
}).done(function(data) {
console.log(data);
});
});
</script>
php-file“gTApi.php”(魔术发生的地方):
<?php
require_once "../../vendor/autoload.php";
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$text = file_get_contents('php://input');
$apKey = '**************************';
$client = new Client(
array(
'headers' => array(
'Accept' => 'application/json'
)
)
);
try {
$response =$client->get('https://translation.googleapis.com/language/translate/v2?key='
. $apKey
. '&source=en&target=es&q=' . $text);
} catch (\Exception $e) {
echo $e->getMessage();
}
$response_body = json_decode($response->getBody(), true);
echo $response_body['data']['translations'][0]['translatedText'];
另一个php文件:
$smarty->assign('text_without_adv', htmlspecialchars((implode(' ', $text_array))));
在页面加载后,我在变量 $ text_without_adv 中的第一个句子后得到意外的标记,并且无法进行翻译,单击按钮时没有任何反应。
例如:
var text_var = JSON.stringify
(“
但她有一个甜心,他说他会去拿球。 /// 令牌 ///所以他去了公园大门,但是'关闭了;所以他爬上树篱,当他到达树篱的顶部时,一位老太太从他面前的堤坝上站起来说,如果他想拿球,他必须在房子里睡三个晚上。他说他会。“);
但主要问题是其他用户发布的其他文本中不会出现错误。我无法理解,来自3个不同用户的3个不同文本有意外令牌,接下来2个没有错误,然后下一个有错误等等。哪个可能是问题?
答案 0 :(得分:0)
在这种情况下,您不需要传递json而只需传递post
数据
要做到这一点
首先更改此行
// to stored your php variable in a js variable
var text_var = "<?php echo $text_without_adv; ?>";
然后
你的ajax中的
$.ajax({
method: 'post',
url: own_script,
data: {
// just use the declared js variable above which contains your php variable at the first place
text: text_var
}
}).done(function(data) {
console.log(data);
});
并在你的php中
而不是
$text = file_get_contents('php://input');
更改为
$text = $_POST['text'];
所以你的代码就像这样
JS
<script type="text/javascript">
$('#some_id').on('click', function(){
var text_var = "<?php echo $text_without_adv; ?>";
var own_script = 'gTApi.php';
$.ajax({
method: 'post',
url: own_script,
data: {
text: text_var
}
}).done(function(data) {
console.log(data);
});
});
</script>
PHP
<?php
require_once "../../vendor/autoload.php";
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$text = $_POST['text'];
$apKey = '**************************';
$client = new Client(
array(
'headers' => array(
'Accept' => 'application/json'
)
)
);
try {
$response =$client->get('https://translation.googleapis.com/language/translate/v2?key='
. $apKey
. '&source=en&target=es&q=' . $text);
} catch (\Exception $e) {
echo $e->getMessage();
}
$response_body = json_decode($response->getBody(), true);
echo $response_body['data']['translations'][0]['translatedText'];