你要求的是不可能的;正如我已经解释过的,PHP 是服务器端,而 JS 是客户端; php 方面所做的任何事情都在页面交付给用户时完成,因此 js 不可能影响 php 方面,除非您的网站或内容交付是在 ajax 中完成的完全,这是一种使用js和php检索信息的方法;简而言之,js向你服务器上的另一个php页面发送请求并返回结果。
然而这要复杂得多,在您对 JS 和 PHP 都比较熟悉之前,我不建议您这样做。
不过,除此之外,php 中有一个解决方案,虽然我现在没有完整的代码。
解决方法是get_browser()的php 4和5函数:
$arr = get_browser(null, true);
$var = "some browser";
if ($arr['parent'] == $var) {
require('/php/file.php');
}
else {
//etc
}
以上是您的答案更新之前;关于上述更新,我无话可说。
更新:关于下面关于 ajax 的 cmets 之一,我将尝试.. 一个示例。我不会尝试称其为“简单”,因为 ajax 绝不是……不过回到正题……
HTML:
<html>
<body>
<div id="main_body">
</div>
</body>
</html>
JS:
//some code to determine user-agent/browser, set variable 'agent' with result
var use_html5;
if (agent == browser) {
use_html5 = 'yes'
}
else {
use_html5 = 'no'
}
function retrv_body() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {//readState 4 is when the request has finished;
//0: request not initialized
//1: server connection established
//2: request received
//3: processing request
//4: request finished and response is ready
document.getElementById('main_body').innerHTML = xmlhttp.responseText;
//set html of div with id 'main_body' to rendering retrieved from php_file_in_same_dir.php
}
}
xmlhttp.open("POST","php_file_in_same_dir.php",true);
//set type of form, boolean is in regards to whether the request is asynchronus or synchronous
//most ajax requests are async, which means they themselves finish executing usually after the function itself has run. I'm not truly knowledgeable regarding this specific thing since I've only ever used async requests, though I would assume being a sync request would mean the function actually waits until it returns a value before it finishes executing.
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//set the headers of the content.
xmlhttp.send("html5=" + use_html5);
//finally, send the data. Depending on the data, the data may need to be url-encoded.
}
retrv_body();
PHP:
<?php
if ($_POST['html5'] == 'yes') {
include('body5.php');
}
else {
include('body_other.php');
}
//body generating code, render page.
?>
以上只是一个例子,我不建议实际使用它,保存retrv_body()函数,并将其更改为您真正可以使用的东西。
希望我在代码中添加的 cmets 将有助于理解;如果还有什么要问的,请随时要求我解释得更彻底。