在 Ajax 加载的 php 模块中使用 javascript,即使请求成功,也返回错误值


Using javascript in a php module loaded by Ajax, to return error values even if the request has been successful

我有一个用php编写的主页,我在其中使用Ajax在给定div中加载"模块"。当然,我剥离了一些代码,但我认为主要的事情是在那里:调用load(),检查成功(或未成功(的ajax请求以及检查从php"返回"的js变量(我将在后面解释(;这是JavaScript:

var ajax_error = ""; //i use this to catch load errors
//.....//
$("#div_target").load("loadmodule.php", {'module':module_number}, function(response, status, xhr)
{
  if (status == "error") //this is for ajax-related errors
  {
    alert('Failed loading module. Error: '+xhr.status + " " + xhr.statusText);
  }
  else 
  {
    //this checks if the variable has been set by the php module to represent an error
    if (ajax_error !== "")
    {
      $("#div_target").html(ajax_error); //show the error instead of the module
      ajax_error = ""; //we reset the variable for future uses
    }
    else
    {
      //do something with the correctly loaded module..
    }
  }
});

"loadmodule.php"是后续的(同样,代码被减少(:

//check for the post value, that should be a positive number as well as check for the file to exist
if ( 
  isset($_POST['module']) 
  && is_numeric($_POST['module']) 
  && ($_POST['module'] > 0) 
  && file_exists("module_" . $_POST['module'] . ".php")
)
{
  //include module
  include("module_{$_POST['module']}.php");
}
else
{
  //error retrieving module
  ?>
  <script type="text/javascript">
    ajax_error = "Cannot load module." ;
  </script>
  <?php
}

这样,如果在检查$_POST['module']时出现任何错误,我们可以"告诉"javascript发生错误只是通过设置变量ajax_error,这将在ajax成功完成请求后被"捕获"。一切都运行良好(这个变量ajax_error的上下文是正确的,即使它看起来不是这样,在这里的剥离代码中:P(,但是..

..我的问题是:这种方法正确吗?这样做有什么问题吗?有没有看起来不太像解决方法的东西?还是在这种情况下我只是尽我所能?

PS:我发现很难给我的问题起个标题,希望没关系:)

是的,这可能有效,但对我来说似乎很丑陋。我建议不要使用 $obj.load,而是使用 $.get。服务器脚本(loadmodule.php(不会返回纯HTML,而是返回具有两个值的JSON:一个布尔标志确定模块是否存在,第二个是HTML内容。

然后,成功处理程序将决定是否将某些内容放入所需的内容,或者如果标志告知该模块不存在,则显示错误消息。