我想制作一个简单的应用程序,将英语翻译成 Yodish,但我不知道如何指示文本框的值。
我正在尝试获取数据文本属性。我管理如何替换正确字段中的文本,但我仍然得到初始值而不是当前值。
这就是我得到的:/image/8LoXe.jpg
更准确地说,我是这样做的:
"data": { text: $("#input").val() }
我想达到这样的效果:https://www.yodaspeak.co.uk/
数据内容如下:/image/LmzSu.jpg
var settings = {
"async": true,
"crossDomain": true,
"url": "https://yodish.p.rapidapi.com/yoda.json?text=Master%20Obiwan%20has%20lost%20a%20planet.",
"method": "POST",
"headers": {
"x-rapidapi-host": "yodish.p.rapidapi.com",
"x-rapidapi-key": "...",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
text: $("#input").val()
}
}
$("#button").click(function() {
$.getJSON(settings).done(function(data) {
$("#result").text(data.contents.translated);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="translator">
<input type="text" id="input" value="Obi wan">
<button id="button">Convert to Yoda-Speak!</button>
<textarea id="result"> Asdasdas. Herh herh herh.</textarea>
</div>
最佳答案
问题是当您定义 settings
的值时,您需要在 click 函数中执行此操作,以便获取输入的当前值(请参阅代码片段)。这就是为什么您总是获得初始值,因为您在更改之前读取了它。
$("#button").click(function() {
var settings = {
"async": true,
"crossDomain": true,
"url": "https://yodish.p.rapidapi.com/yoda.json",
"method": "POST",
"headers": {
"x-rapidapi-host": "yodish.p.rapidapi.com",
"x-rapidapi-key": "...",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
text: $("#input").val()
}
}
$.getJSON(settings).done(function(data) {
$("#result").text(data.contents.translated);
})
console.log(settings.data)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="translator">
<input type="text" id="input" value="Obi wan">
<button id="button">Convert to Yoda-Speak!</button>
<textarea id="result"> Asdasdas. Herh herh herh.</textarea>
</div>
关于javascript - 如何使用 api 设置要翻译的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57887466/