本实例有两个文件,一个php处理文件,一个html请求文件。 代码如下:

my_parse_file.php

<?php 
echo \'Thank you \'. $_POST[\'firstname\'] . \' \' . $_POST[\'lastname\'] . \', says the PHP file\';
?>

example.html

<html>
<head>
< >
function ajax_post(){
    // Create our  HttpRequest  
    var hr = new  HttpRequest();
    // Create some variables we need to send to our PHP file
    var url = \"my_parse_file.php\";
    var fn = document.getElementById(\"first_name\").value;
    var ln = document.getElementById(\"last_name\").value;
    var vars = \"firstname=\"+fn+\"&lastname=\"+ln;
    hr.open(\"POST\", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");
    // Access the   event for the  HttpRequest  
    hr.  = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById(\"status\").innerHTML = return_data;
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById(\"status\").innerHTML = \"processing...\";
}
</ >
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
First Name: <input id=\"first_name\" name=\"first_name\" type=\"text\">  <br><br>
Last Name: <input id=\"last_name\" name=\"last_name\" type=\"text\"> <br><br>
<input name=\"myBtn\" type=\"submit\" value=\"Submit Data\"  =\"ajax_post();\"> <br><br>
<div id=\"status\"></div>
</body>
</html>
收藏 打印