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

时间:2013-03-08 15:34:55

标签: php javascript ajax

我有一个用PHP编写的主页面,我使用Ajax在给定的div中加载“模块”。当然,我删除了一些代码,但我认为主要的事情是:调用load(),检查成功(或不是)ajax请求以及检查js变量“返回”来自php(我将在稍后解释);这是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']时出现任何错误,我们可以通过设置变量ajax_error“告诉”javascript发生错误,该变量将在ajax之后被“捕获”成功完成了请求。一切都运行良好(这个变量ajax_error的上下文是正确的,即使它看起来不是真的,在这里的剥离代码中:P),但是......

..我的问题是(是):这种方法是否正确?这样做有什么问题吗?有什么东西看起来不像是一种解决方法吗?或者我只是在这种情况下做得最好?

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

1 个答案:

答案 0 :(得分:0)

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

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

相关问题