原始php文件结构:(注意<?php require '_nodetype_setother.js';?>与“});”之间是有换行的)
$("input[name=nodetype]").click(function(){
var name = $("#name").val();
var nodetype = $(this).val();
<?php require '_nodetype_setother.js';?>
});
插入的JS文件内容:(注意下面的代码的最后一行是没有空行的)
var input_width = $("input:text[name='width']");
var input_height = $("input:text[name='height']");
input_width.val('');
input_height.val('');
最后运行的php文件的源代码如下:
$("input[name=nodetype]").click(function(){
var name = $("#name").val();
var nodetype = $(this).val();
var input_width = $("input:text[name='width']");
var input_height = $("input:text[name='height']");
input_width.val('');
input_height.val('');});
有没有发现在原始php文件结构中的最后一行的“});”与“input_height.val('');”怎么到了一行去了?在原php文件中“});”与<?php require '_nodetype_setother.js';?>是存在换行的,那么为什么之前存在换行的而最后得到的源代码中却没有了换行了呢?
这个问题涉及到 PHP 的 require 机制和服务器端与客户端代码执行的差异。
1:PHP require 是服务器端操作:
<?php require '_nodetype_setother.js';?> 在服务器端执行
服务器会读取 _nodetype_setother.js 文件的内容并将其直接插入到 PHP 代码的位置
这个过程发生在发送给浏览器之前
2:文件结尾的处理:
如果 _nodetype_setother.js 文件的最后没有空行,那么插入的内容会紧挨着后面的 });
浏览器接收到的最终代码就是合并后的结果
解决方案:
1:在 JS 文件末尾添加空行:即在 _nodetype_setother.js 文件末尾添加一个空行,确保插入后有换行
2:修改 PHP 代码添加换行:?php echo " "; ?>
注意除了会过滤掉换行,同时还会过滤掉空格,比如<?php require '_nodetype_setother.js';?>前面存在的空格,在发送到浏览器之后这个空格就不见了。
