首先让我说我是 Ajax 的新手。我一直在阅读来自 jquery.com 的文章和一些教程,但我还没有弄清楚这是如何实现我想要实现的目标的。
我正在尝试使用 Google 的 Weather 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 PHP 代码:http://pastebin.com/aidXCeQg
可以在这里查看:http://downloadlive.org/weather.php
有人可以帮我解决这个问题吗?
非常感谢
最佳答案
你只需要返回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;
});
关于php - 新手的 jQuery Ajax 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7459756/