如何将响应从 PHP 发送到 Ajax?



这个JavaScript代码使用POST方法将数据从表单发送到PHP,PHP在数据库中检查数据是否为真。但是我不知道如何将 PHP 的响应发送回 JS,即获取成功。有人可以解释一下吗?

.JS:

$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(){
//check if what response is   
} 
});

ajaxsubmit.php:

<?php
session_start();
//connect
$username =$_POST['username'];
$password =$_POST['password'];  
$sql = "SELECT * FROM user WHERE email ='$username' OR username ='$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if(!$row = mysqli_fetch_assoc($result)){     
//response error
} else{
//response success
}
?>

你在 php 中回显的任何内容都会被发送回 ajax。

if(!$row = mysqli_fetch_assoc($result)){
echo 0;
}
else{
echo 1;
}

success: function(response){
//check if what response is
console.log( response );
} 

你必须在 PHP 中回显一些东西才能得到一些东西的返回:

if(!$row = mysqli_fetch_assoc($result)){
//response error
echo 'there is a problem';
} else {    
//response success
echo 'yippee!';
}

然后,您可以按如下方式记录返回:

$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(data){ // 'data' is the variable holding the return from PHP's echo
//check if what response is   
console.log(data);
} 
});

确保在浏览器的开发人员工具中观察 AJAX 请求/响应。确保在项目中包含了 jQuery 库。控制台将显示错误。AJAX 需要一个 Web 服务器。

警告小鲍比说你的脚本有SQL注入攻击的风险。了解 MySQLi 的预准备语句。即使逃脱绳子也不安全!

危险永远不要存储纯文本密码!请使用PHP 的内置函数来处理密码安全性。如果您使用的是低于 5.5 的 PHP 版本,则可以使用password_hash()兼容包。在散列之前,无需转义密码或使用任何其他清理机制。这样做会更改密码并导致不必要的额外编码。

您可以使用响应参数退出方法。 比如:

阿贾克斯提交.php

if(!$row = mysqli_fetch_assoc($result)){     
exit('error');  //exit with response 'error'
} else{
exit('success'); //exit with response 'success'
}

.JS

$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(response){
//check if what response is   
console.log(response);
} 
});

最新更新