可能很多人都和我遇到相同的問題:
一般解決這個問題的辦法就是,在php代碼中向前臺echo一段js代碼,如:
echo '<script>alert("提示消息!");</script>';
這樣echo出來前臺是正常顯示的,但是用layer.msg();就會沒有提示,解決方法如下:
首先要echo layer.msg();的頁面必須引入jquery.js及layer.js
所以我們可以直接在後臺這樣寫
echo '<script type="text/javascript" src="/Public/js/jquery.js"></script>';
echo '<script type="text/javascript" src="/Public/js/layer/layer.js"></script>';
然後
echo '<script>$(document).ready(function(){layer.msg("'.$message.'");});</script>'; //$message 是你要提示的內容 這裏我做了一個變量.
解釋一下 後臺使用layer.msg();最外層一定要用ready函數,否則js庫資源文件引入的延遲就會導致layer.msg();執行失敗;undefined;
爲了方便我直接在我項目的common.php封裝了success和error
protected function leError($message, $jumpUrl = '', $time = 2000){
echo '<script type="text/javascript" src="/Public/js/jquery.js"></script>';
echo '<script type="text/javascript" src="/Public/js/layer/layer.js"></script>';
echo '<script>$(document).ready(function(){layer.msg("'.$message.'");setTimeout(function(){window.location.href="'.$jumpUrl.'";},'.$time.')});</script>';
}
protected function leSuccess($message, $jumpUrl = '', $time = 2000) {
echo '<script type="text/javascript" src="/Public/js/jquery.js"></script>';
echo '<script type="text/javascript" src="/Public/js/layer/layer.js"></script>';
echo '<script>$(document).ready(function(){layer.msg("'.$message.'");setTimeout(function(){window.location.href="'.$jumpUrl.'";},'.$time.')});</script>';
}
調用的時候可以繼承這個函數所在的類
$this->leError('提示信息',U('Index/index'));
如果不想讓它跳轉,而是直接返回上一級代碼可以改成這樣的:
protected function leError($message, $jumpUrl = '', $time = 2000){
echo '<script type="text/javascript" src="/Public/js/jquery.js"></script>';
echo '<script type="text/javascript" src="/Public/js/layer/layer.js"></script>';
if($jumpUrl != ''){
echo '<script>$(document).ready(function(){layer.msg("'.$message.'");setTimeout(function(){window.location.href="'.$jumpUrl.'";},'.$time.')});</script>';
}else{
echo '<script>$(document).ready(function(){layer.msg("'.$message.'");setTimeout(function(){window.history.back(-1);},'.$time.')});</script>';
}
}
這樣就方便在其它代碼處 直接調用;
希望對你有用!