[英]Is there a more proper way to handle errors using AJAX?
我從沒在這里問過任何問題,但是有些問題困擾着我。
您看,我在用PHP玩了大約一年。 在學習PHP,JQuery,MySQL等時,我已經做了一個很大的項目-它遠非完美,甚至還沒有完成,但是它有效,並且我一直在嘗試在增加新功能的同時改進現有代碼。 這是一個基於文本的瀏覽器MMORPG游戲(仍在開發中),如果您想要一個鏈接,我會提供,但是我沒有來這里進行宣傳。
事實是,我在程序PHP中感覺還不錯(盡管我仍然在重復代碼方面遇到問題),所以我認為現在是時候轉向OOP了。 我從理論上理解它,知道一些基礎知識,並且在實踐中我正在慢慢地進步,但是在走得太遠之前,我需要您的建議。
在我最初的帶有程序代碼的游戲中,我經常按照以下方式進行操作:
現在,這是處理錯誤的正確方法嗎? 還是應該完全不同地編碼? 這種方法在OOP中仍然有效嗎?
讓我向您展示這個示例的含義,此刻我正在玩弄( 為簡單起見,請忘記代碼的安全性甚至有用性 ):
index.php
<!DOCTYPE html>
<html lang="pl-PL">
<head>
<meta charset="UTF-8">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<p id="error-message"></p>
<p id="success-message"></p>
<form id="registration-form" method="post">
<input type="text" placeholder="Account Name" name="nickname"></input>
<input type="text" placeholder="Password" name="password"></input>
<input type="text" placeholder="E-mail" name="email"></input>
<button type="submit">Register</button>
</form>
</div>
</body>
</html>
User.php
<?php
class User{
//register method
public function register($nickname, $password, $email){
$result = array("success" => 0, "message" => "");
//example validation
if($nickname==123){
$result["message"] = "Could not register.";
}
else{
//add user to the database
//sql code here
$result["success"] = 1;
$result["message"] = "Registration successful.";
}
return $result;
}
}
?>
registerProcessing.php
<?php
require_once 'User.php';
$user = new User();
echo json_encode($user->register($_POST["nickname"], $_POST["password"], $_POST["email"]));
?>
script.js
$(function() {
$("#wrapper").on("submit", "#registration-form", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "registerProcessing.php",
data: $("#registration-form").serialize(),
dataType: "json",
success: function(result){
if(result.success){
$("#success-message").html(result.message);
}
else{
$("#error-message").html(result.message);
}
}
});
});
});
正確的方法是研究已經制作成javascript / jQuery的ajax回調和狀態,然后使用它們。 如果您需要更高級的功能,則需要通過后端發送一些標頭,以強制某些狀態,這些狀態可以由適當的回調或自定義的回調處理。
您可以使用主要由主要js庫/框架處理的HTTP狀態代碼 (甚至是遵循HTTP代碼模式的XMLHttpRequest 純自身,請參閱MDN )。
直接回答您的問題,不,是不對的。 您的ajax使用主回調(成功)並按返回值進行處理。 它是可行的,但是缺少有關回調的最佳實踐,就像我上面提到的那樣。
您可以執行的示例:
$("#wrapper").on("submit", "#registration-form", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "registerProcessing.php",
data: $("#registration-form").serialize(),
dataType: "json",
success: function(result){
$("#success-message").html(result.message);
},
error: function(result){
$("#error-message").html(result.message);
}
});
});
要么
$("#wrapper").on("submit", "#registration-form", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "registerProcessing.php",
data: $("#registration-form").serialize(),
dataType: "json",
statusCode: {
404: function() {
$("#error-message").html('NOT FOUND');
},
200: function(result) {
$("#success-message").html(result.message);
},
500: function(result) {
$("#error-message").html(result.message);
}
}
});
});
或以XMLHTTPREQUEST為例:
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
switch (request.status){
case 404:
break;
case 500:
break;
case 200;
break
}
要添加到@CarlosAlexandre關於使用HTTP狀態代碼處理錯誤的答案:在過渡到OOP編程時,您應該意識到,使用異常處理來傳遞錯誤條件已成為一種最佳實踐。 這可能是這樣的:
User.php
class User{
//register method
public function register($nickname, $password, $email){
//example validation
if($nickname==123){
throw new InvalidArgumentException('Invalid username');
}
//add user to the database
//sql code here
}
}
registerProcessing.php
require_once 'User.php';
$user = new User();
$response = array(
'success' => 0,
'message' => 'Unknown error',
);
try {
$user->register($_POST["nickname"], $_POST["password"], $_POST["email"]);
$response['success'] = 1;
$response['message'] = 'Registration successful.';
} catch (Exception $exception) {
$response['message'] = $exception->getMessage();
}
echo json_encode($response);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.