如何使用$.post请求将用户名和密码传递给服务器url?
我想从该请求返回 true 或 false。
$.post("dtbs.php",{username:userName,password:password},function(result){
});
上面的代码表示,但我想将 true 或 false 值从该请求传递到文本文件。 我很困惑该怎么做?
下面是我的脚本:
<script>
$(document).ready(function(){
$("#loginBtn").click(function(){
var userName = $("#inputlUsername3").val();
var password = $("#inputlPassword3").val();
if(userName && password) {
//your php request goes here and return true or false or any ohter response as per your need
$.post("dtbs.php",{username:userName,password:password},function(result){
});
$.ajax({url: "response.txt", success: function(result){
if(result === 'true') {
alert("Redirect it to dashboard");
} else {
alert("Show error");
}
}});
} else {
alert("Plz fill all the field");
}
});
});
</script>
下面是dtbs.php
<?php
$uname=$_POST['txtuname'];
$pwd2=$_POST['txtpwd2'];
$con=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("onlineshop",$con);
$r=mysql_query("select password from users where username='$uname'",$con);
$row = mysql_fetch_row($r);
$val=$row[0];
if($val!="")
{
if($pwd2==$val)
{
session_start();
$_SESSION['username']=$uname;
$myfile= fopen("response.txt", "w") or die("unable to open file");
$txt="true";
fwrite($myfile, $txt);
fclose($myfile);
}
else {
$myfile= fopen("response.txt", "w") or die("unable to open file");
$txt="false";
fwrite($myfile, $txt);
fclose($myfile);
}
}
else {
$myfile= fopen("response.txt", "w") or die("unable to open file");
$txt="false";
fwrite($myfile, $txt);
fclose($myfile);
}
?>
给我建议解决方案。
最佳答案
如果用户名/密码成功,dtbs.php 应该返回结果,而不是写入文本文件。
<script>
$(document).ready(function(){
$("#loginBtn").click(function(){
var userName = $("#inputlUsername3").val();
var password = $("#inputlPassword3").val();
if(userName && password) {
$.post("dtbs.php", username:userName, password:password}, function(result){
if(result === 'true') {
alert("Redirect it to dashboard");
}
else {
alert("Show error");
}
});
} else {
alert("Plz fill all the field");
}
});
});
</script>
<?php
$uname=$_POST['username'];
$pwd2=$_POST['password'];
$con=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("onlineshop",$con);
$r=mysql_query("select password from users where username='$uname'",$con);
$row = mysql_fetch_row($r);
$val=$row[0];
if($val!="")
{
if($pwd2==$val)
{
session_start();
$_SESSION['username']=$uname;
echo 'true';
}
else {
echo 'false';
}
}
else {
echo 'false';
}
?>
总的来说,您的代码存在以下问题:
- 不要使用 msql_ 函数,这些函数已被弃用。
- SQL 注入(inject)问题。
- 将密码以纯文本形式存储在数据库中。
- 在没有密码的情况下以 root 身份连接到 mySql。
关于php - 将用户名/密码传递给服务器 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078239/