在我的项目中,我使用 ajax 来处理表单。现在我想获取要处理的 Post 数据。当不允许使用 Jquery 时,我使用 Javascript。但是 Ajax 返回整个页面,我该如何解决。
我的控制器:
class Form extends Controller {
function __construct() {
parent :: __construct();
$this->load->model('Form_model');
}
function index() {
$this->loadForm();
}
function loadForm() {
$this->load->view('form_view');
}
function ajax_add_form_content() {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest") {
echo $_POST['fullname'] . '+' . $_POST['subject'];
} else {
echo '0';
}
}
}
我的观点:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Form view</title>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "<?php echo base_url().'index.php/form/ajax_add_form_content'?>";
var fn = document.getElementById("txtFullName").value;
var ln = document.getElementById("txtSubject").value;
var vars = "fullname="+fn+"&subject="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
return false;
}
</script>
</head>
<body>
<div id="form">
<span id='status' ></span>
<form class="form" method="post">
<p class="formName">contact</p>
<p class="formDesc">contact us</p>
<div class="form_elements">
<div class="textField">
<label>Full name</label>
<input id="txtFullName" class="inputText required" type="text" maxlength="255" size="28" name="txtFullName">
</div>
<div class="textField">
<label>Subject</label>
<input id="txtSubject" class="inputText required" type="text" maxlength="255" size="28" name="txtSubject">
</div>
</div>
<div class="form_submit">
<input id="btnSubmit" type="submit" value="Send" name="btnSubmit" onClick="javascript:ajax_post();">
</div>
</form>
<div id='display'>
</div>
</div>
</div>
</body>
</html>
谢谢你的帮助 !