[英]How do I get data from an input field into my ajax request?
I am trying to get the data from a text field into my ajax request so that I can get a response from an API.我正在尝试将文本字段中的数据获取到我的 ajax 请求中,以便我可以从 API 获得响应。 But I have little experience with JS so I can't figure it out.
但是我对JS的经验很少,所以我无法弄清楚。
I am using the materialize framework.我正在使用物化框架。
HTML: HTML:
<div class="input-field">
<label for="country">Autocomplete</label>
<input type="text" id="country" class="autocomplete">
</div>
JS: JS:
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'https://sandbox.iexapis.com/stable/search/**{I need the text from what the user has put in here}**?token='myiextoken',
success: function(response) {...
You can use jquery val() method to get the input value, then you need to encode this value using encodeURIComponent before passing it into your url.您可以使用jquery val()方法获取输入值,然后您需要使用encodeURIComponent对该值进行编码,然后再将其传递给您的 url。
$(document).ready(function() {
//Autocomplete
$(function() {
var inputValue = $('#country').val();
var url = 'https://sandbox.iexapis.com/stable/search/'
+ encodeURIComponent(inputValue)
+ '?token='myiextoken';
$.ajax({
type: 'GET',
url: url,
...
use val()
to get the value of the input.使用
val()
获取输入的值。
const value = $("#country").val();
and use it using string template literal并使用字符串模板文字使用它
$(document).ready(function() { //Autocomplete const value = $("#country").val(); $(function() { $.ajax({ type: 'GET', url: `https://sandbox.iexapis.com/stable/search/${value}token='myiextoken`, success: function(response) {... */
<div class="input-field"> <label for="country">Autocomplete</label> <input type="text" id="country" class="autocomplete"> <button> click </button> </div>
If you want to use native JavaScript, just write:如果要使用原生 JavaScript,只需写:
document.getElementById('country').value;
just add the line只需添加行
$.ajax({
type: 'GET',
url: "https://sandbox.iexapis.com/stable/search/" + $('#country').val() + "?token='myiextoken'",
success: function(response) {...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.