2012-10-26 47 views
2

我正在使用自提交表單來處理數據,但我現在需要分別處理它,所以現在我需要提交表單,返回結果並將其放入div 。看來使用AJAX是一種很好的方法,可以將數據返回到表單所在的原始頁面。我已經看了很多例子,並且我不太瞭解如何去做或者真的如何去做。通過Ajax提交表單並更新結果div

假設我想將此表單數據從index.php發送到我的流程頁面twitterprocess.php我需要做什麼並使其返回以顯示處理的數據。

<form method="POST" action="twitterprocess.php"> 
    Hashtag:<input type="text" name="hashtag" /><br /> 
    <input type="submit" value="Submit hashtag!" /> 
</form> 

這就是我一直用來顯示結果。

<?php foreach($results as $result) { 
    $tweet_time = strtotime($result->created_at);?> 
    <div> 
    <div class="tweet"> <?php echo displayTweet($result->text),"\r\n"; ?> 
    <div class="user"><?php echo "<strong>Posted </strong>" . date('j/n/y H:i:s ',$tweet_time) ?><strong> By </strong><a rel="nofollow" href="http://twitter.com/<?php echo $result->from_user ?>"><?php echo $result->from_user ?></a></div> 
    </div> 
    <br /> 
<? } ?> 

我是新來的AJAX,但任何指導,將不勝感激

回答

5

*當您使用AJAX時,在其他頁面上生成的輸出是此頁面的結果。 *現在,當你想通過使用AJAX發佈數據和檢索結果,然後在你的html的表單部分不要使用type =「submit」按鈕,而只需要輸入type =「button」。

*因爲您要通過AJAX代碼觸發操作,操作屬性應該留空。

*好休息下面的代碼片段的所有解決方案:

下面是用AJAX沿HTML代碼

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Simple Form Handling Through AJAX</title> 
<script type="text/javascript"> 
    function loadXmlDoc(fname, lname){ 
     var xmlhttp; 
     if (window.XMLHttpRequest){ 
      xmlhttp = new XMLHttpRequest(); 
     } 
     else{ 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange = function(){ 
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ 
       document.getElementById("ajaxify").innerHTML =    xmlhttp.responseText; 
      } 
     } 
     xmlhttp.open("POST", "demo_ajax3.php", true); 
     xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     xmlhttp.send("fname=" + fname + "&" + "lname=" + lname); 
    } 
</script> 
</head> 

<body> 
<p> 
    <span id="ajaxify">&nbsp;</span> 
</p> 
<form id="frm" action="#"> 
    <input type="text" name="fn" /> 
    <input type="text" name="ln" /> 
    <input type="button" name="submit" value="submit" onclick="loadXmlDoc(fn.value, ln.value)" /> 
</form> 
</body> 
</html> 

下面是在上面的代碼中使用PHP代碼

<?php 
$fname = $_POST["fname"]; 
$lname = $_POST["lname"]; 
echo "Hello " . $fname . " " . $lname; 
?> 
+0

感謝這個好例子。我會投票,但唉,我的排名太低 – user1711576

+0

一個問題。什麼是200的? '如果(xmlhttp.readyState == 4 && xmlhttp.status == 200){' – user1711576

+0

200意味着狀態爲「OK」,即AJAX函數已經得到了所需要的,4表示對服務器的請求正確完成並且響應來自該服務器已準備好使用。 – Isank

0

您可以使用jQuery的,舉例來說,

function doPost(formdata){ 
    var url="/twitterprocess.php"; 
    var senddata={'data':formdata}; 
    $.post(url,senddata,function(receiveddata){ 
     dosomethingwithreceiveddata(receiveddata); 
    } 

你的php將得到JSON形式送出數據。您可以處理併發送適當的迴應。這種反應可以通過用接收到的數據來處理。

+0

我必須得到表單發佈到jquery而不是php文件 – user1711576

+0

您需要添加腳本標籤內的函數,並添加onclick事件到您的按鈕來調用腳本中的處理函數。 – specialscope

+0

'$ .ajax({... data:$(「my_form_id」)。serialize()...})' – Rolice

2

爲您的提交按鈕分配一些id,我會使用id =「submit」和一些id爲您的文本字段(我使用id =「text」);

客戶端JS:

$("#submit").click(function() { 
    var postData = new Object(); //for complex-form 
    postData.hashTag = $("#text").val(); 
    $.ajax({ 
     type: 'POST', //or 'GET' if you need 
     contentType: "application/json; charset=UTF-8", //i use json here 
     dataType: "json", 
     url: "some_url", 
     data: JSON.stringify(postData), //or smth like param1=...&param2=... etc... if you don't want json 
     success: function (response) { 
      //handle response here, do all page updates or show error message due to server-side validation 
     }, 
     error: function() { 
      //handle http errors here 
     } 
    }); 
    return false; //we don't want browser to do submit 

});因此,如果用戶啓用了js =您的代碼將執行ajax請求,否則 - 將發出常規發佈請求;

在服務器端,您必須處理ajax並定期提交不同的內容以使其在兩種情況下都能正確工作。我不擅長php,所以不能在這裏做任何建議

0

我發現Ajax Form插件是一個很好的工具。

http://www.malsup.com/jquery/form/#tab4

一個基本的代碼示例可能是:

$(document).ready(function() { // On Document Ready 
    var options = { 
     target: '#output1', // ID of the DOM elment where you want to show the results 
     success: showResponse 
    }; 

    // bind form using 'ajaxForm'  
    $('#myForm1').ajaxForm(options); 
}); 

// the callback function 
function showResponse(responseText, statusText, xhr, $form) { 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
    '\n\nThe output div should have already been updated with the responseText.'); 
} 

所有你的PHP文件中需要做的就是echohtml(或文本)回來,你想在你的DIV展現形式後已提交。

0

如果你不想使用jquery嘗試這種在純粹的JavaScript

function SendData(Arg) { 
    xmlhttp=null; 
    var uri = "/twitterprocess.php"; 
    if(window.XMLHttpRequest) { 
     xmlhttp=new XMLHttpRequest(); 
    } else if(window.ActiveXObject) { 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    if(xmlhttp!=null) { 
     xmlhttp.onreadystatechange = function() { 
     if(xmlhttp.readyState==4) { 
      if(xmlhttp.status==200) { 
       var xmlDoc = xmlhttp.responseXML; 
       var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue; 
       var Xml2String; 
       if(xmlDoc.xml) { 
        Xml2String = xmlDoc.xml 
       } else { 
        Xml2String = new XMLSerializer().serializeToString(xmlDoc); 
       } 
       document.getElementById("CellData").value=Xml2String; 
      } else { 
       alert("statusText: " + xmlhttp.statusText + "\nHTTP status code: " + xmlhttp.status); 
      } 
     } 
    } 
}