あなたが求めるものは不可能です。すでに説明したように、PHP はサーバー側であり、JS はクライアント側です。ページがユーザーに配信されるまでに php 側で行われたことはすべて終了しているため、サイトまたはコンテンツ配信が完全に ajax で行われない限り、js が php 側に影響を与えることは不可能です。情報を取得するための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 に関する以下のコメントの 1 つに関して、私は試みます..例。私はそれを「単純」と呼ぼうとはしません。なぜなら 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()関数を保存し、実際に使えるものに変更することはお勧めしません。
コードに付けたコメントが理解に役立つことを願っています。ご不明な点がございましたら、お気軽にお問い合わせください。