我有我的第一个AJAX调用与jQuery的设置和工作良好。我需要做的最后一个改变是检查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页面的结果(数据)进行分支。
发布于 2014-10-27 04:06:28
而不是从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
}https://stackoverflow.com/questions/26580976
复制相似问题