jQueryAJAX-基于PHP页面数据的有条件成功结果

jQuery AJAX - conditional success result based on data from PHP page

本文关键字:有条件 成功 结果 数据 基于 PHP jQueryAJAX-      更新时间:2023-09-26

我用jQuery设置了第一个AJAX调用,并且运行良好。我需要做的最后一个更改是检查被调用的PHP页面的结果是否有任何数据库错误,并在需要时显示错误。

以下是我当前的Javascript,其中有一些注释,我想根据结果进行分支:

<script type="text/javascript">
    $(document).ready(function() {
        $("#storeManager").change(function(){
            var storeManager = $("#storeManager").val();
            $.post('editProject.php', { type: 'storeManager', storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
                // if there was a database error from the editProject.php page it will be returned in this format:
                // Error: Database Error 456
                // If there is an "Error: " string in the result I would like to do the following
                $("#ajaxAlert").addClass("alert alert-danger");
                $("#ajaxAlert").html(data);

                // If there is no "Error: " string in the result I would like to do the following
                $("#storeManagerRow").addClass("success");
                $("#storeManagerRow").removeClass("danger");
                $("#ajaxAlert").hide();
            }).fail(function () {
                // no data available in this context
                $("#storeManagerRow").addClass("danger");
                $("#ajaxAlert").addClass("alert alert-danger");
                //append error to the div using its ID
                $("#ajaxAlert").html(data);
            });
         }); 
    }); 
</script>

我是jQuery和AJAX的新手,边做边学——只是不知道如何根据PHP页面的结果(数据)进行分支。

不从PHP脚本返回html,而是返回一个JSON对象。

为了获得成功,您可以返回一个data对象,如下所示:

{
  html: '<p>lorem ipsum</p>'
}

对于应用程序错误的结果,您可能会有一个data对象,如下所示:

{
  error: true,
  html: '<p>Error: Database Error 456</p>'
}

在回调中,只需检查error属性的存在:

if (data.error) {
  $("#ajaxAlert").addClass("alert alert-danger").html(data.html);
  // ...
  return; // stop the execution of this function right here
}