簡體   English   中英

新手的jQuery Ajax帖子

[英]jQuery Ajax post for newbie

首先讓我說我是Ajax的新手。 我一直在閱讀來自jquery.com和一些教程的文章,但我還沒有弄清楚它是如何工作的我想要實現的。

我正在嘗試使用Google的Weather API XML獲取搜索城市的天氣, 而無需刷新頁面。

我設法檢索Weather 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

有人可以幫我解決這個問題嗎?

非常感謝

你只需要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()完成此操作.serialize()容易。

$(".submit").click(function(){
    $.ajax({
        type : 'post',
        url:"weather.php",
        data: $(this.form).serialize(),
        datatype: "text",
        success: function(result){
            $(".wedata").html(result);
        }
    });

    return false;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM