2 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
首先,如果您從 javascript 請求某些內(nèi)容,則無法通過 php 重定向用戶,請從 addUser.php 中刪除此行
header('Location: ./dashboard.php?user='.$username);
現(xiàn)在要將結(jié)果從 php 返回到客戶端,您必須DIE使用帶有值的 php,最好的方法是 JSON
在 addUser.php 檢查你想要什么并返回如下值:
<?php
session_start();
/* Include the database connection file (remember to change the connection parameters) */
require './db_inc.php';
/* Include the Account class file */
require './account_class.php';
$type = $_POST['type'];
$username = $_POST['uname'];
$password = $_POST['password'];
$comp = $_POST['company'];
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = $pdo->query("SELECT * FROM accounts WHERE email ='".$email."'");
$account = new Account();
// Will print all the values received.
$newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);
if(intval($newId) > 0) // if user created
die(json_encode(array('status' => 'ok')));
else
die(json_encode(array('status' => 'error')));
?>
然后更改您的客戶端,如下所示:
$(document).on('click', '#createUserBtn', function(e){
e.preventDefault();
$.ajax({
url:'addUser.php',
type:'post',
data:$('#addUser').serialize(),
dataType: "json", // <- Add this line
success:function(response){ // <- add response parameter
//Here check result
if(response['status'] == 'ok')
toastr.success("User successfully added!");
else
toastr.warning('Uh-oh! Something went wrong with adding this user!');
},
error: function(){
},
statusCode: { // <- Add this property
500: function() {
toastr.warning('Uh-oh! Something went wrong with adding this user!');
}
}
});
});

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以使用http_response_code()返回 HTTP 錯(cuò)誤代碼(通常代碼 500 :內(nèi)部服務(wù)器錯(cuò)誤)。
您可以使用 try/catch 塊來做到這一點(diǎn):
try
{
...
$account = new Account();
// Will print all the values received.
$newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);
header('Location: ./dashboard.php?user='.$username);
}
catch(Exception $e)
{
http_response_code(500);
exit();
}
- 2 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)