Php 通过Ajax提交表单并更新结果div

Php 通过Ajax提交表单并更新结果div,php,ajax,Php,Ajax,我曾经使用一个自提交表单来处理数据,但现在我需要单独处理它,所以现在我需要提交一个表单,返回结果并将其放置在div中。使用AJAX似乎是一种很好的方法,可以将数据返回到表单所在的原始页面。我看了很多例子,但我真的不知道该怎么做,也不知道它是如何工作的 假设我想将此表单数据从index.php发送到我的流程页面twitterprocess.php我需要做什么,并让它返回以显示已处理的数据 <form method="POST" action="twitterprocess.php">

我曾经使用一个自提交表单来处理数据,但现在我需要单独处理它,所以现在我需要提交一个表单,返回结果并将其放置在div中。使用
AJAX
似乎是一种很好的方法,可以将数据返回到表单所在的原始页面。我看了很多例子,但我真的不知道该怎么做,也不知道它是如何工作的

假设我想将此表单数据从
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新手,但如果您能提供任何指导,我将不胜感激。例如,您可以使用jQuery

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

您的php将以JSON格式获取senddata。您可以处理并发送适当的响应。该响应可以由dosomethingwithreceiveddata处理。

为提交按钮分配一些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请求,否则-将发出常规post请求


在服务器端,您必须处理ajax和常规提交,以使其在这两种情况下都能正常工作。我不擅长php,因此无法在此提供任何建议

我发现Ajax表单插件是一个很好的工具

一个基本的代码示例可以是:

$(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文件所要做的就是在表单提交后返回要在DIV中显示的
echo
html(或文本)。

*使用AJAX时,在其他页面上生成的输出就是此页面的结果

*现在,当您想通过使用AJAX发布数据和检索结果时,在html的表单部分,不要使用type=“submit”作为按钮,而只需使用type=“button”

*操作属性应该留空,因为您将通过AJAX代码触发操作

*请将所有解决方案放在下面的代码段中:

下面是HTML代码和AJAX

<!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>

通过AJAX进行简单的表单处理
函数loadXmlDoc(fname,lname){
var-xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=新的XMLHttpRequest();
}
否则{
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById(“ajaxify”).innerHTML=xmlhttp.responseText;
}
}
open(“POST”,“demo_ajax3.php”,true);
setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
xmlhttp.send(“fname=“+fname+”&“+”lname=“+lname”);
}

下面是上面代码中使用的PHP代码

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

如果不想使用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);
            }
        }
    }
}

我是否必须将表单发布到jquery而不是php文件中?您需要在脚本标记中添加函数,并将onclick事件添加到按钮中,以在脚本中调用处理程序函数。
$.ajax({…数据:$(“my_form_id”).serialize()…})
感谢这个伟大的示例。我会投票,但可惜我的排名太低了一个问题。200是干什么用的?”如果(xmlhttp.readyState==4&&xmlhttp.status==200){'200表示状态为“OK”,即AJAX函数已获得所需内容,4表示对服务器的请求已正确完成,服务器的响应已准备就绪。