私はphpで書かれたメインページを持っています.Ajaxを使って特定の.xmlファイルに「モジュール」をロードします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: 質問にタイトルを付けるのが難しいと思いました。大丈夫だといいのですが:)