Javascript 如何在php中替换文件内容而不出现并发问题
我想为left.php的链接附加一个HTML属性id=“active” left.php应该只有一个id为“active”的链接 下面的代码实际上是按照我的要求工作的,但是过了一会儿,由于并发问题,left.php的内容完全丢失了 我如何解决这个问题 我认为我们可以有一个java脚本解决方案在客户端处理这个问题。 请让我知道最好的解决方案与例子 谢谢大家Javascript 如何在php中替换文件内容而不出现并发问题,javascript,php,Javascript,Php,我想为left.php的链接附加一个HTML属性id=“active” left.php应该只有一个id为“active”的链接 下面的代码实际上是按照我的要求工作的,但是过了一会儿,由于并发问题,left.php的内容完全丢失了 我如何解决这个问题 我认为我们可以有一个java脚本解决方案在客户端处理这个问题。 请让我知道最好的解决方案与例子 谢谢大家 <?php $searchF1 = ' id="active"'; $replaceW1 = ''; $searchF = base
<?php
$searchF1 = ' id="active"';
$replaceW1 = '';
$searchF = basename(__FILE__).'"';
$replaceW = $searchF.' id="active"';
$myfile = fopen( 'left.php', 'rt' );
flock( $myfile, LOCK_SH );
$file = file_get_contents( 'left.php' );
fclose( $myfile );
$file = str_replace( $searchF1, $replaceW1, $file );
$file = str_replace( $searchF, $replaceW, $file );
file_put_contents('left.php', $file);
include('left.php');
?>
我认为您正在尝试将当前页面的链接设置为活动。在这种情况下,你做错了。所有逻辑必须在
left.php
文件中。您可以这样做:
$pages = array(
'firstPage.php' => 'First Page',
'secondPage.php' => 'Second Page',
'thirdPage.php' => 'Third Page',
);
$currentParsedUrl = parse_url("http://$_SERVER[SERVER_NAME]$_SERVER[REQUEST_URI]");
$currentPath = ltrim($currentParsedUrl['path'], '/');
foreach ($pages as $path => $name) {
echo '<a href="/' . $path . '"';
echo $currentPath == $path ? ' id="active"' : '';
echo '>' . $name . '</a>';
}
$pages=数组(
'firstPage.php'=>'firstPage',
'secondPage.php'=>'secondPage',
'thirdPage.php'=>'Third Page',
);
$currentParsedUrl=parse_url(“http://$\u服务器[服务器名称]$\u服务器[请求URI]”);
$currentPath=ltrim($currentParsedUrl['path'],'/');
foreach($path=>$name的页面){
回声';
}
现在,您所要做的就是将
left.php
文件包含在您希望显示这些链接的任何位置。而不是文件内容和包含try eval。然后,您将跳过写入文件,并将其用作模板
在下一个版本中,请尝试使用过程或OOP。我通过在我的left.php末尾添加下面的脚本来实现客户端 这是工作,我认为这是一个很好的解决方案,最好的性能。多谢各位
<script>
var name = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
var pattern = /.php/;
var exists = pattern.test(name);
if(exists){ $('a[href$="'+name+'"]').css('font-weight', 'bold');}
else{ $('#left').find('a:first').css('font-weight', 'bold');}
</script>
var name=window.location.href.substr(window.location.href.lastIndexOf(“/”)+1);
var模式=/.php/;
var exists=pattern.test(名称);
如果(存在){$('a[href$=“'+name+'“]').css('font-weight','bold');}
else{$('#left').find('a:first').css('font-weight','bold');}
我认为更好的方法是使用jQuery试试这个(“#active”).not(“:first”).remove();Malith,你能详细说明一下你的方法吗?我很乐意这么做。谢谢Matei Mihai,你让我跳出了思维定势。我会尽力让你们都知道的。当然,理查德,我很高兴你们提出了宝贵的建议。非常感谢您花时间回答。很好的一天!