我正在尝试实现一个简单的 javascript 程序,我在其中对 php 脚本进行 ajax 调用。我确保页面不会自行刷新。所以,现在如果我在 php 中使用 echo 函数,那么它就无法正常工作。
$("#check").on('click',function(){
//alert("hello");
var user_name=document.getElementById("user_name").value;
var pwd=document.getElementById("pwd").value;
$.ajax({
url:'checkUser.php',
type:'POST',
data:{
user_name:user_name,
pwd:pwd
},
success:function(){
alert("hello"); //This section works fine so the php file is getting called
}
});
return false;
})
检查用户.php
<?php require 'database.php';
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
//Database is getting connected properly
$user_name=$_POST['user_name'];
$password=$_POST['pwd'];
echo("<script>console.log('PHP:');</script>"); //not getting displayed on console
$sql="Select * from login where User_name='$user_name' and Password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
echo $count; //not getting displayed on console
?>
如果我想使用回显功能,我应该怎么做?谢谢!
最佳答案
您没有通过 success() 函数传递结果。您必须显示页面响应的结果。你可以这样做:
$("#check").on('click',function(){
//alert("hello");
var user_name=document.getElementById("user_name").value;
var pwd=document.getElementById("pwd").value;
$.ajax({
url:'checkUser.php',
type:'POST',
data:{
user_name:user_name,
pwd:pwd
},
success:function(data){
alert(data); //data will contain the echo value
}
});
return false;
})
“数据”变量将始终包含打印在页面上的响应,包括错误,因此如果您将其用作验证,请务必考虑到这一点。
关于javascript - echo 不适用于不刷新页面的 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43642967/