前端使用Vue向后端发送请求
const app = new Vue({
el: '#app',
data: {
words: '',
result: '',
timer: null,
to: 'en'
},
watch: {
async words(newValue) {
if (!newValue)
{
this.result = ''
return
}
clearTimeout(this.timer)
this.timer = setTimeout(async () => {
const res = await axios.get('./php/P032_Translate.php', {
params: {
q: newValue,
from: 'auto',
to: this.to,
}
})
this.result = res.data.trans_result[0].dst
}, 500)
},
async to(newTo) {
if (!this.words) {
this.result = ''
return
}
const res = await axios.get('./php/P032_Translate.php', {
params: {
q: this.words,
from: 'auto',
to: newTo,
}
})
this.result = res.data.trans_result[0].dst
}
}
})
后端返回(部分代码)
function translate($query, $from, $to)
{
$args = array(
'q' => $query,
'appid' => APP_ID,
'salt' => rand(10000,99999),
'from' => $from,
'to' => $to,
);
$args['sign'] = buildSign($query, APP_ID, $args['salt'], SEC_KEY);
$ret = call(URL, $args);
$ret = json_decode($ret, true);
return $ret;
}
$q = $_GET['q'];
$from = $_GET['from'];
$to = $_GET['to'];
echo json_encode(translate($q, $from, $to));
return;