gpt4 book ai didi

javascript - PHP 不向 AJAX 返回数据

转载 作者:行者123 更新时间:2023-12-01 00:00:01 25 4
gpt4 key购买 nike

我正在测试一个登录表单,该表单通过 Ajax 将数据提交到 PHP 处理文件。一旦我单击提交按钮,它只会将我重定向到 PHP 文件,而不是从 PHP 返回数据。该表单位于引导模式内部。我是 jquery 和 ajax 的新手,所以我希望有人能提供帮助。谢谢

HTML

<form action="login-process.php" id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>

<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>

<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>

JQuery 脚本放置在 jquery.js cdn 之后的站点页脚

$(document).ready(function(){

// Process form
$('#test-form').submit(function(event){

// get form data
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};

// process the form
$.ajax({
type : 'POST', // define the HTTP method we want to use
url : 'process.php', // url to send data
data : formData, // data object
dataType : 'json', // what type of data to expect back from server
encode : true
})
// using done promise call back
.done(function(data){

// log data to console
console.log(data);

if (data.email-msg) {
alert("success");
}

});

// stop the form from submitting and refresing the page
event.preventDefault();
});
});

流程.php

<?php 

$data = array(); // array to hold pass back data

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

$email = $_POST['login-email'];
$password = $_POST['login-pass'];

$data['email-msg'] = $email;
$data['pw-msg'] = $password;

echo json_encode($data);
} ?>

最佳答案

试试这个兄弟

$(document).ready(function(){
$('#test-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"action="login-process.php" ",
method:"POST",
data:$(this).serialize(),
success:function(data){
console.log("data send");
}
})
});
});
<form id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>

<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>

<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>

关于javascript - PHP 不向 AJAX 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60795699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com