首先,让我说我是Ajax新手。我一直在阅读jquery.com的文章和一些教程,但我还没有弄清楚它是如何在我努力实现的目标上工作的。
我正在尝试使用Google的天气API XML,来获取搜索城市的天气,而不需要刷新页面.。
我成功地检索了天气XML并解析了数据,但是每次我搜索不同的位置时,页面都会重新加载,因为我的天气小部件在一个选项卡下面。
这就是我的HTML中的内容:
<script type="text/javascript">
$(document).ready(function(){
// FOR THE TAB
$('.tab_btn').live('click', function (e) {
$('.tab_content').fadeIn();
});
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
aysnc:false,
success:function(result){
$(".wedata").html(result);
}});
});
});
</script>
<style>.tab_content{display:none;}</style>
</head><body>
<input type="button" value="Show Content" class="tab_btn">
<div class="tab_content">
<h2>Weather</h2>
<form id="searchform" onKeyPress="return submitenter(this,event)" method="get"/>
<input type="search" placeholder="City" name="city">
<input type="hidden" placeholder="Language" name="lang">
<input type="submit" value="search" class="submit" style="width:100px">
</form>
<div id="weather" class="wedata">
</div>
</div>这是我正在做的实际演示:http://downloadlive.org。
现在,如果我在搜索表单中添加action="weather.php",我就会得到结果,但是我会被重定向到weather.php,这是合乎逻辑的。在没有action="weather.php"的情况下,每次我搜索我所使用的索引时,都会将不应该使用的/?city=CITY+NAME加起来。这应该添加到weather.php中,得到结果,然后返回到我的索引中,如果这有意义的话?
这是我的weather.php:http://pastebin.com/aidXCeQg的php代码
可以在这里查看:http://downloadlive.org/weather.php
有人能帮我解决这个问题吗?
非常感谢
发布于 2011-09-18 05:56:40
您只需要从return false事件处理程序中提取click;。这将防止发生默认操作-在这种情况下,提交表单。另外,删除async: false设置。您几乎从不需要同步ajax请求。
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});或者,您可以将一个参数名称传递给回调,然后使用event.preventDefault()实现与上面相同的结果:
$(".submit").click(function(e){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
e.preventDefault();
});您需要用POST发送表单数据。使用.serialize()进行这一操作非常容易。
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
data: $(this.form).serialize(),
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});https://stackoverflow.com/questions/7459756
复制相似问题