Javascript数据在搜索中被逐字发送,而不是完整的单词
正在尝试使用ajax和jquery访问yahoo weather api。如果使用submit按钮搜索和提交,效果很好,但我希望仅使用enter键进行搜索。一次只需要一个字母,而不是完整的搜索词Javascript数据在搜索中被逐字发送,而不是完整的单词,javascript,jquery,ajax,Javascript,Jquery,Ajax,正在尝试使用ajax和jquery访问yahoo weather api。如果使用submit按钮搜索和提交,效果很好,但我希望仅使用enter键进行搜索。一次只需要一个字母,而不是完整的搜索词 function makeAjaxCall(url, methodType,callback){ var xhr = new XMLHttpRequest(); xhr.open(methodType, url, true); xhr.send();
function makeAjaxCall(url, methodType,callback){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
console.log("xhr done successfully");
var resp = xhr.responseText;
var respJson = JSON.parse(resp);
callback(respJson);
} else {
console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
}
function processUserDetailsResponse(userData){ //Callback function
console.log(userData.query.results.channel.astronomy);
}
$('#inpt_search').keypress(function(e){
if(e === 'Enter'){
var city = $("#sunrise").value;
console.log(city);
e.preventDefault();
}
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20astronomy%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+ city +'%2C%20%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
makeAjaxCall(url, "GET", processUserDetailsResponse); enter code here //calling api using ajax
});
我不会使用“keypress”事件,因为如果不冻结整个字段,就无法阻止其默认行为。而是使用“keyup”。下面是一个可能的解决方案(将submit
功能替换为任何适合您需要的功能):
$(“输入”).focus()打开(“键控”,函数(ev){
ev.preventDefault();
//如果键是ENTER
如果(ev.which==13){
提交($(this.val());
}
});
功能提交(val){
$(“p”)。文本(val);
}
完成后按ENTER键。
据我所知,按下Enter键后,您需要进行ajax调用和更新。请尝试以下代码,它仅在按下enter键时调用API
$('#inpt_search').keypress(function(e){
if(e.which === 13){
var city = $("#sunrise").value;
e.preventDefault();
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20astronomy%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+ city +'%2C%20%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
makeAjaxCall(url, "GET", processUserDetailsResponse);
}
});
如果(e.keyCode==13)使用
而不是像符咒一样工作。非常感谢。