2010-09-16 136 views
1

將以下PHP表單提交轉換爲Ajaxy類型表單有多簡單。PHP表單提交 - 轉換爲jQuery .Ajax

這裏是PHP:

<?php //Send Tweet 
    if(isset($_POST['submit'])) { 
    $qtweet = $_REQUEST['tweet']; 
    $connection->post('statuses/update', array('status' => $qtweet)); 
    echo "<div style='padding-bottom: 5px; color: #0099FF;'>Updated your Timeline Successfully.</div>"; 
    } 
?> 

和HTML表單:

<form id="tweethis" method='post' action='index.php'> 
    <textarea style="width: 346px;" name="tweet" rows="5" id="tweet" ></textarea> 
    <br /> 
    <span id="charLeft">140</span> Characters left 
    <br /> 
    <input type='submit' value='Tweet This!' name='submit' id='submit' /> 
    <br /> 
</form> 

我想這樣的頁面犯規需要重新加載使用Ajax。

回答

0

很容易。

使用$ .ajax,並檢出serialize()函數以轉換您的表單數據。您還需要防止默認行爲和事件冒泡。這tutorial是相當不錯的。

在ajax調用中,您必須指定處理請求的PHP頁面。該腳本將處理表單提交,就像正常的PHP表單一樣,然後迴應任何輸出。該輸出將被傳回給呼叫客戶端。

1
$(document).ready(function() { 
    $("#tweethis").submit(function() { 
     $.post('index.php', $("#tweet").val(), function(html) { 
      $("#resultDiv").html(html); 
     }); 
     return false; // prevent normal submit 
    }); 
}); 

看看$.ajax$.post(和$.get)包裝它。