今天遇到个问题,同样一个html页面,直接访问html js代码生效,通过thinkphp的controller的
fetch()得到的html中的js不生效,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="/tp5/public/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert('hello');
var url=$("#div1").attr("href");
$.ajax({url:url,success:function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<button id="btn3">flush</button>
<div id="div1" href="http://www.yx.com/tp5/public/index.php/teacher/klass_controller/"></div>
</body>
</html>
经查看浏览器的源码发现,经过thinkphp controller->fetch()的html中的js代码被修改为
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="/tp5/public/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert('hello');
var url=$("#div1").attr("href");
$.ajax(/tp5/public/index.php/teacher/KlassController/add1.html});
});
});
</script>
</head>
<body>
<button id="btn3">flush</button>
<div id="div1" href="http://www.yx.com/tp5/public/index.php/teacher/klass_controller/"></div>
</body>
</html>
其中js代码中的
$.ajax({url:url,success:function(result){
$("#div1").html(result);
}});
被修改为
$.ajax(/tp5/public/index.php/teacher/KlassController/add1.html});
导致浏览器解析js的时候出现语法错误,从而js代码不起作用。
估计是thinkphp的view模板解析器把 { 当成解析替换的开始了。
用link连接js代码文件即可解决这问题。