javascript - 有没有更合适的方法来使用 AJAX 处理错误?

标签 javascript php jquery ajax

我从来没有在这里问过任何事情,但有件事让我烦恼。

你看,我玩 PHP 大约有一年了。在学习 PHP、JQuery、MySQL 等的过程中,我给自己做了一个相当大的项目——它远非完美,甚至还远未完成,但它有效,而且我不断尝试改进现有代码,同时添加新功能。这是一款基于文本的浏览器MMORPG游戏(还在开发中),如果你想要链接,我会提供,但我不是来这里推广的。

问题是,我对过程式 PHP 感觉还不错(尽管我仍然有重复代码的问题),所以我决定是时候转向 OOP 了。我在理论上理解它,了解基础知识,并且在实践中慢慢进步,但在走得太远之前我需要你的建议。

在我最初的程序代码游戏中,我经常按照以下方式做一些事情:

  • 用户访问一个页面,例如 shop.php。打开网站时,shop.php 从数据库中检索可购买的商品列表。网站上有空白的 #success-message#error-message 段落。
  • 然后,用户可以从商店中选择他想要购买的商品 - 单击该商品会触发 javascript,并对 buy-item.php 进行 AJAX 调用,期望返回 json
  • 在 buy-item.php 中,我正在创建一个数组,例如 $result("success"=> 0, "message"=> "")
  • buy-item.php 检查玩家是否能买得起该元素、背包中有空间等,如果有一个条件不满足,则 $result["message"] 设置为,例如,“你需要更多的黄金”。如果满足所有条件,则将 result["success"] 设置为 1,将 $result["message"] 设置为“购买成功”。最后,它会将 json_encode($result) 回显到 AJAX。
  • 在 AJAX 中 成功: 我检查 if(result.success),并采取相应行动 - 如果购买成功,我会执行 $("# error-message").html(result.message),如果成功,我会将 result.message 放在“#success-message”中(我可以在同一个中显示错误和成功消息我猜想,但对我来说单独执行更简单,因为这些消息的样式不同,例如,成功为绿色,错误为红色)。

现在,这是处理错误的正确方法吗?或者我应该完全不同地编码?这种方法在 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 回调和状态并使用它们。如果您需要更高级的功能,则需要 send by backend一些 header 强制某些状态可以通过适当的回调或自定义回调来处理。

您可以使用HTTP status codes主要使用主要的 js 库/框架进行处理(甚至是 XMLHttpRequest pure itself that follow the HTTP pattern of codes, see 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
}

关于javascript - 有没有更合适的方法来使用 AJAX 处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44057135/

相关文章:

javascript - 复选框限制功能发生后复选框变得不可点击reactjs

javascript - jquery 自动完成接受而不从下拉列表中选择

javascript - 图像拉伸(stretch)和裁剪以适合精确尺寸

php - codeigniter 中的语言没有按预期工作

javascript - 页脚的动态绝对位置,缺少像素 - 无限滚动

jquery - Facebook Oauth 使用 Jquery Mobile 登录 #_=_

javascript - 如何在一个函数下合并 javascript 中的加载事件和更改事件?

javascript - JavaScript 中的范围(我认为?!)挑战

php - 如何在mysql中插入多维数组?

php - 在给定索引的字符串中获取字符的最快方法(PHP)