我有一个表单,它接受一个城市作为输入,然后我使用jQuery通过SongKick接口获取该位置的ID,然后使用该ID获取该位置的未来事件(也使用SongKick API和jQuery )。
我遇到的问题是,当我输入一个城市并点击submit时,对SongKick API的第一次调用永远不会返回结果,但是如果我再次点击submit而没有更改城市文本,它就可以正常工作(之后每次都可以使用相同的城市文本)。
任何帮助都是非常感谢的。
HTML代码:
<form action="#" onsubmit="doSearch(this.locationtext.value);">
<input onfocus="this.value=''" type="text" size="60" name="locationtext" value="Enter a City" />
<input type="submit" value="Make it rain" />
</form>JavaScript代码:
function doSearch(locations) {
jQuery.getJSON("http://api.songkick.com/api/3.0/search/locations.json?query=" + locations + "&apikey=eRACBJEh2i3NOewK&jsoncallback=?", function(locdata){
// THIS CODE NEVER RUNS THE FIRST TIME
// get metro area ID from SongKick result
var getID = locdata.resultsPage.results.location[0].metroArea.id;
// pass ID to another SongKick API call to get events at location
jQuery.getJSON("http://api.songkick.com/api/3.0/metro_areas/" + getID + "/calendar.json?apikey=eRACBJEh2i3NOewK&jsoncallback=?", function(data){
// do whatever with result
});
});}
发布于 2012-03-02 12:31:20
在阻止表单的提交事件后,您必须检查输入值:
<form action="#" id="doSearch">
<input onfocus="this.value=''" type="text" size="60" name="locationtext" value="Enter a City" />
<input type="submit" value="Make it rain" />
jQuery(function($){
$("#doSearch").submit(function(e){
e.preventDefault();//prevent the form to be submitted
var location = $(e.target).find('[name="location"]').val();
//do what you need with location
});
})发布于 2012-03-02 12:32:19
我认为这可能是由于您处理表单提交的方式。不应使用onsubmit属性,而应尝试使用不显眼的方法附加事件处理程序。jQuery让这一切变得非常简单。
<form action="#">
<input type="text" size="60" name="locationtext" placeholder="Enter a City" />
<input type="submit" value="Make it rain" />
</form>
$("form").submit(function() {
var loc = $("input[name='locationtext']", this).val();
$.getJSON("http://api.songkick.com/api/3.0/search/locations.json?jsoncallback=?", {
query: loc,
apikey: "eRACBJEh2i3NOewK"
}, function(data) {
var getID = data.resultsPage.results.location[0].metroArea.id;
alert(getID);
});
return false;
});注意事件处理程序是如何返回false的。这会阻止默认操作(提交表单)运行
JSFiddle演示- http://jsfiddle.net/VSt3R/2/
https://stackoverflow.com/questions/9527888
复制相似问题