我想在不提交/重新加载页面的情况下获取输入的值,然后使用它向 API 发出 get 请求。这是 HTML:
<form name="music_title" id="search_it">
<input name="song_name" id="search_song" placeholder="Enter song to add" onsubmit="return searchSg()"/>
</form>
这是我为此编写的 JavaScript
searchSg = function(){
oForm = documents.forms[0]
SC.get("/tracks", {q: oForm.elements["song_name"].value , limit: 20}, function(tracks){
$(tracks).each(function(index, track) {
//do stuff with track info
});
});
}
$("#search_song").submit(searchSg() { return false; });
但是这些都没有被执行,表单仍在提交中。我尝试过使用 ajax 调用,但根本没有执行。我已经确保静态文件夹的路径工作正常,并且其他功能也可以正常工作。似乎每当我尝试发出 ajax 请求时,javascript 就不起作用,现在我也无法让表单以这种方式获取数据。
最佳答案
试试这个:
$("#search_it").submit(function(ev){
//Do stuff here
var songName = $('#search_song').val();
$.get('/tracks', {q : songName, limit: 20}, function(tracks){
//Do something with the response(tracks) here
});
//You can call ev.preventDefault() but return false will do that for you..
return false;
});
关于javascript - 如何从输入中获取值并使用 jQuery 提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30382427/