你所求是不可能的;正如我已经解释过的,PHP 是服务器端,而 JS 是客户端;php 端所做的任何事情都在页面交付给用户时完成,因此 js 不可能影响 php 端,除非您的网站或内容交付完全在 ajax 中完成,这是一种使用 js 的方法和php 检索信息;简而言之,js 向您服务器上的另一个 php 页面发送请求并返回结果。
然而,这要复杂得多,在您对 JS 和 PHP 都更加熟悉之前,我不建议您这样做。
然而,除此之外,php 中有一个解决方案,虽然我现在没有完整的代码。
解决方案是 php 4 和 5 的函数get_browser()
:
$arr = get_browser(null, true);
$var = "some browser";
if ($arr['parent'] == $var) {
require('/php/file.php');
}
else {
//etc
}
以上是您的答案更新之前;关于上述更新,我无话可说。
更新:关于下面关于 ajax 的评论之一,我将尝试.. 一个例子。我不会尝试称它为“简单”,因为 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()
功能,并将其更改为您真正可以使用的东西。
希望我在代码中的注释有助于理解;如果还有什么要问的,请随时要求我更彻底地解释。