Html代码
<div class="container">
<?php echo $_POST['name']; ?>
<form method="POST" id="reg-form" action="register">
<label>Full Name:</label>
<input class="register-form-input" type="text" name="name" id="name"><br>
<label>Username:</label>
<input class="register-form-input" type="text" name="username" id="username"><br>
<label>Email:</label>
<input class="register-form-input" type="email" name="email" id="email"><br>
<label>ID Number:</label>
<input class="register-form-input" type="text" name="idnumber" id="idnumber"><br>
<label>Password:</label>
<input class="register-form-input" type="password" name="password" id="password"><br>
<label for="name">Repeat Password:</label>
<input class="register-form-input" type="password" name="password1" id="password1"><br><br>
<input type="submit" name="submit" id="register-submit" onclick="ajax_post();">
</form>
<?php echo $_POST['name']; ?>
</div>
Javascript文件
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "register/index";
var name = document.getElementById("name").value;
var username = document.getElementById("username").value;
var vars = "name="+name+"&username="+username;
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;
console.log(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.querySelector('#reg-form').onsubmit=function(){
return false;
}
注册控制器
<?php
class Register extends Controller{
public function __construct(){
parent::__construct();
echo $_POST['name'];
}
public function index(){
echo $_POST['name'];
$this->view->render('register/index',false);
$this->model->run();
echo $_POST['name'];
}
public function run(){
}
}
问题是,当我在控制台中返回Data(ajax Response)时,它显示整个内容,并且我写的所有内容echo $ _POST ['name']仅出现在控制台响应中,在页面上它是未定义的。如果你需要解释我会更详细。只是$ _POST ['name']在页面上未定义,但在控制台中没有。
答案 0 :(得分:-1)
Ajax不是时间旅行。
这就是:
发出第二个请求不会更改历史记录。第一个请求的结果未更改,仍显示在页面中。
如果要加载整个新页面,请不要使用Ajax。
如果你想根据你得到Ajax请求的响应来修改用户已经在查看的页面,那么你必须编写JavaScript(在你的onreadystatechange
函数中)来操作页面的DOM。