gpt4 book ai didi

javascript - 如何获取ajax请求的输入值

转载 作者:行者123 更新时间:2023-11-28 08:34:28 24 4
gpt4 key购买 nike

对于我正在使用的 API,我不知道如何将文本框中的值获取到我的搜索查询中。在此示例中,我想获取有关伦敦的信息,但如何将 London 替换为 city 文本输入中的值。

$.getJSON('https://api.search?near=LONDON&v=20120101',
<body onLoad="init()">
Search the place: <input type="text" id="city" class="cjtxt"></input>

我尝试执行以下操作:

$.getJSON('https://api.search?near=+city&v=20120101', function(){});

但是没有成功..我做错了什么,我该如何解决这个问题?

有什么想法吗?

最佳答案

最简单的版本

您向输入字段添加一个事件监听器,每次更改时,您都会收集该值,并将其放入 Ajax 请求中。

$("#city").change(function(){
var city = $(this).val();
$.getJSON('https://api.search?near=' + city + '&v=20120101',
function(data){
// Your data will be available here
});
});

新增功能

您应该使用某种验证逻辑 fx 来保护请求。它的长度不能少于 2 个字符,或者仅在用户停止输入 500 毫秒时才请求。

示例 #1 - 至少 2 个字符:

$("#city").change(function(){
var city = $(this).val();
if(city && city.length >= 2){
$.getJSON('https://api.search?near=' + city + '&v=20120101',
function(data){
// Your data will be available here
});
}
});

示例 #2 - 用户停止输入后的请求(500 毫秒):

var cityTimeoutId;
$("#city").change(function(){
// Stop the 'Timeout' if it haven't already been fired
clearTimeout(cityTimeoutId);
var city = $(this).val();
// Set the timeout, meaning it will run this method in 500ms
cityTimeoutId = setTimeout(function(){
$.getJSON('https://api.search?near=' + city + '&v=20120101',
function(data){
// Your data will be available here
});
}, 500);//<- The 500ms is set here, as the last param of the timeout function
});

关于javascript - 如何获取ajax请求的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21407661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com