<html>
<body>
<div id="main_login_div">
<form name="form1" id="main_form" method="post" target="_parent" action="checklogin.php">
<input name="myusername" type="text" id="myusername" placeholder="User Name Here">
<input name="mypassword" type="password" id="mypassword" placeholder="Password Here">
<input type="submit" name="Submit" id="gogogo" value="Login">
<p id="msg" name="msg"><?php echo $_GET['msg']; ?></p>
</form>
</div>
</body>
</html>
所以这是我的登录表单,我使用GET
方法来获取消息密码是否错误,所以问题是,当我点击提交页面刷新时,我不想让我的页面重新加载,是否有任何方法可以获得结果而无需重新加载Ajax
和JavaScript
而不是JQuery
下面是一个使用简单JavaScript的简单ajax请求
function request(url, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState !== XMLHttpRequest.DONE) return;
switch (req.status) {
case 200:
return callback(null, req.responseText);
case 404:
return callback(Error('Sorry, 404 error'));
default:
return callback(Error('Some other error happened'))
}
};
req.open("GET", url, true);
req.send();
return req;
}
你可以这样使用
var req = request('/some-data.json', function (err, res) {
// check for error
if (err) return console.error(err);
// do something with the data
console.log(JSON.parse(res));
});
注意,你需要做一些额外的研究来支持旧的IE浏览器。
据我所知,有三种方法可以在客户端和服务器之间传递信息:
- 页面加载 AJAX
- Websockets
AJAX是普通的JavaScript,根据您的浏览器支持,您可能需要以几种不同的方式实现它来支持旧的和新的。大多数人使用jQuery的$.ajax()函数,因为它更容易编写(和阅读)。
如果你不想要AJAX或页面重载,唯一的其他选择是使用websockets,但有很多依赖于特定的服务器端和客户端软件。它相对较新,所以没有很多"初学者指南"。这可能会让您开始:http://www.phpbuilder.com/articles/application-architecture/optimization/creating-real-time-applications-with-php-and-websockets.html
唯一的方法是使用AJAX,使用JavaScript也更容易。使用jQuery库中的$.post()
非常容易。示例(使用jQuery):
<script type="text/javascript">
$("form#main_form").submit(function(e){
e.preventDefault(); //stops the form submitting normally
var formData = $(this).serializeArray(); //make an array of the form data
$.post("checklogin.php", formData, function(response){ //POST the form data to 'checklogin.php'
console.log(response); //output PHP response to console
});
});
</script>