我正在进行jquery ajax调用,如下所示。
$("form.form-signin").submit(function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url : "scripts/logincontroller.php",
type: "POST",
dataType :"json",
data: {
username : $form.find("input[name='username']").val(),
password : $form.find("input[name='password']").val()
},
success: function(response){
$("div.jumbotron div#error_panel").css("display","block");
var err_msg = '';
if(response.errors != null){
for(i = 0; i<response.errors.length;i++){
err_msg += response.errors[i]+"</br>";
}
$("div.jumbotron div#error_panel div#message").empty().append(err_msg);
return;
}else{
$("div.jumbotron div#error_panel div#message").empty().append("ok");
}
},
error: function(xhr, status, errorThrown){
alert(errorThrown+status);
$("div.jumbotron div#error_panel").css("display","block");
}
});
});
现在我有以下课程。 此类连接到数据库并在成功时返回db对象,否则返回字符串错误。
//DBConfiguration.class.php
namespace db;
class DBC{
const username = "root";
const password = "****";
const host = "localhost";
const schema = "mydb";
static function connect(){
try{
$dbh = new \PDO('mysql:host='.self::host.';dbname='.self::schema, self::username, self::password, array(
\PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}catch (\PDOException $e){
return "Failed to connect to database";
}
}
}
该类调用上面的connect并返回结果。
//Authenticator.php
namespace db;
include "DBConfiguration.class.php";
class Authenticator{
public function isValidUser($username,$password){
$result = array();
$dbh = DBC::connect();
if(is_string($dbh) && $dbh === "Failed to connect to database"){
$err = array();
$err[] = "Oops! Something went wrong. We are working on it";
$result["errors"] = $err;
}else{
$err = array();
$err[] = "connected successfully";
$result["errors"] = $err;
}
return $result;
}
}
//LOGINCONTROLLER.PHP
header("Content-Type: application/json", true);
include "db\Authenticator.php";
$authenticator = new \db\Authenticator();
echo json_encode($authenticator ->isValidUser($_POST["username"],$_POST["password"]));
当我故意更改密码而无法连接到db时,我收到正确的错误消息。但是当它成功时(在这种情况下我从connect()方法返回db对象),我得到'意外令牌&lt;'。
奇怪的是,当我将所有这些类放在logincontroller.php而不是induvidual名称空间时,我能够运行代码。
此代码有问题吗?
答案 0 :(得分:1)
我找到了答案。以下行导致了问题。
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
上面的代码必须是
$dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
当我从命名空间类调用它时,PDO必须引用全局PDO类。