我相信这对你们来说很容易,但我正在努力解决这个问题。只是想在这里做一个简单的ajax post请求到php文件。
我可以看到ajax请求正在运行,因为我从我的php脚本中获取了有效数据(我通过将结果回显到页面来验证这一点)。但是,我的ajax回调没有触发。见下文:
使用Javascript:
var request;
$(document).ready(function() {
$('#loginform').submit(function(e) {
if (request)
request.abort();
var $form = $(this);
var $inputs = $form.find("input, select, button");
$inputs.prop("disabled", true);
var serializedData = $form.serialize();
request = $.ajax({
url: "/login.php",
type: "post",
data: serializedData,
timeout: 10000,
success: function() {
alert("success");
// $("#result").html('Submitted successfully');
},
error: function() {
alert("failure");
// $("#result").html('There is error while submit');
}
});
});
PHP
<?php echo 'foo'; exit(); ?>
考虑到有很多例子,我几乎觉得这很愚蠢,但我无法让这个为我的生活工作。建议?
修改 包含的html(大多数css类来自bootstrap btw)
<div style='background-color: #193048; width: 100%; height: 500px; background-repeat: no-repeat; background-position: center center; background-size: cover;'>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<h1 class="text-center login-title whiteFont">Sign in to continue</h1>
<div class="account-wall">
<div align='center'>
<img class="profile-img" align='center' src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
alt="">
</div>
<form id="loginform" class="form-signin" method="post" >
<input type="text" name='emailTxt' class="form-control" placeholder="Email" required autofocus>
<input type="password" name="passTxt" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="login" id="loginBtn" >
Sign in</button>
<label class="checkbox pull-left">
<input type="checkbox" value="remember-me" >
<label class="whiteFont">Remember me</label>
</label>
<a href="#" class="pull-right need-help"><label class="whiteFont">Need Help?</label></a><span class="clearfix"></span>
</form>
</div>
</div>
</div>
</div>
答案 0 :(得分:2)
您需要将从服务器返回的数据作为参数传递给回调
var request;
$(document).ready(function() {
$('#loginform').submit(function(e) {
if (request)
request.abort();
var $inputs = $form.find("input, select, button");
$inputs.prop("disabled", true);
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/login.php",
type: "post",
data: serializedData,
timeout: 10000,
success: function(data, status, xhr) { // <---- changes made here
alert("success");
// $("#result").html('Submitted successfully');
},
error: function() {
alert("failure");
// $("#result").html('There is error while submit');
}
});
});
答案 1 :(得分:2)
.submit
最有可能导致回发,取消你的JS。将preventDefault
添加到函数的开头:
e.preventDefault();