0

我正在学习教程,当我单击提交按钮时,什么也没有发生。我添加了一个警报以查看该功能是否运行。它运行警报。

[代码]

<!-- THE HTML PAGE AND JAVASCRIPT -->

<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){


   // added by me to test
    alert("Hello");

    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // 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 onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = 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...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Your First Name: <input id="first_name" name="first_name" type="text" /> 
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>

[php]

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

我在这里做错了什么?它根本没有给出任何错误。请帮我。

http://jsfiddle.net/HjhV4/

4

1 回答 1

0

尝试这个

html

<h2>Ajax Post to PHP and Get Return Data</h2>
<form id="form">
Your First Name: <input id="first_name" name="first_name" type="text" /> 
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data">
<br /><br />
</form>
<div class="status"></div>

javascript

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#form") .submit(function(){
var first_name  = $("#first_name") .val();
var last_name  = $("#last_name") .val();

var s = {
"first_name":first_name,
"last_name":last_name
}

$.ajax({
url:'action.php',
type:'post',
data:s,
beforeSend: function (){
        $(".status") .html("<img src=\"style/img/ajax/load1.gif\" alt=\"Loading ....\" />");
        },
success:function(data){
$(".status").html(data);
}
});

});
})
</script>
于 2013-08-27T01:04:05.920 回答