我在使用带有 Ajax 的 POST 然后使用 PHP 进行处理时遇到问题。
我目前正在研究这个示例并对其进行调整以满足我的需求: http ://coursesweb.net/ajax/ajax-post-php
我已经完全复制了 2 个示例文件,当我提交表单时,浏览器只会显示 PHP 文件的文本内容。
该页面底部的演示工作正常,所以我认为我的服务器配置一定有问题?(Apache 2.2.22 与 PHP 5.3.16)
标准 Ajax 请求正常工作,就像普通的 PHP Post 表单一样,问题仅在使用 Ajax 发布时出现。
任何帮助都是极好的!
如果你不想点击链接:test_form.php
<?php
// if data are received via POST
if (isset($_POST['nume']) && isset($_POST['mesaj'])) {
// get data into variables, deleting the html tags
$nume = strip_tags($_POST['nume']);
$mesaj = strip_tags($_POST['mesaj']);
// if the form fields are completed
if (strlen($nume)>0 && strlen($mesaj)>0) {
echo 'Welcome <b>'. $nume. '</b><br />The message you`ve sent: <pre>'. $mesaj. '</pre>';
}
else {
echo 'Fill in all form fields';
}
}
?>
ajax_form.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example Ajax and Form</title>
<script type="text/javascript"><!--
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // calls the function for the XMLHttpRequest instance
// gets data from form fields, using their ID
var nume = document.getElementById('nume').value;
var mesaj = document.getElementById('mesaj').value;
// create pairs index=value with data that must be sent to server
var the_data = 'nume='+nume+'&mesaj='+mesaj;
request.open("POST", php_file, true); // sets the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // sends the request
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<div id="resp">Here will be displayed the server response.</div><br />
<form action="test_form.php" method="post" name="form1" onsubmit="ajaxrequest('test_form.php', 'resp'); return false;">
Your name: <input type="text" name="nume" id="nume" size="20" maxlength="33" /><br />
Your message:<br />
<textarea name="mesaj" id="mesaj" cols="25" rows="4"></textarea><br />
<input type="submit" value="Send" />
</form>
</body>
</html>