サーバー側 (PHP) のコードは、コードをブラウザー側のコードに変換する前に読み取られることを覚えておく必要があります。JavaScriptはブラウザ側で操作...
一次元的には、JavaScript を PHP に渡すことはできません。
でも...
Ajax を使用すると、JSON を使用して JavaScript データを PHP ページに送信し、応答を JavaScript メソッドに戻すことができます。これはあなたのニーズに合うと思います。必要に応じて、簡単な例を提供できます。
//-- 以下の例:
JavaScript:
//Ajax Method
function processAjax(queryString, processDiv, responseDiv) {
responseDiv.innerHTML = '';
var myAjax;
try {
// Modern Browsers-->
myAjax =new XMLHttpRequest();
} catch (e) {
// antique ie browsers-->
try {
myAjax =new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
myAjax =new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
document.getElementById('processDiv').innerHTML="";
alert("Your browser malfunctioned! Please try again. Consider installing a modern browser if the problem persists.");
return false;
}
}
}
myAjax.onreadystatechange = function() {
if (myAjax.readyState == 4) {
var ajaxResponse = myAjax.responseText;
responseDiv.innerHTML = ajaxResponse;
processDiv.innerHTML = "";
//NOTE: HERE IS WHERE AJAX IS FINISHED, SO IF YOU WANT TO DO SOMETHING ELSE HERE YOU CAN!
//POST PROCESSING----->
// IE: alert('I am finished processing now!');
// or call another function:
// anotherFunction();
} else {
processDiv.innerHTML = '<img src="http://www.mysite.com/images/loadingicon.gif" alt="processing....." />';
}
}
myAjax.open("GET", queryString, true);
myAjax.send(null);
}
function sendStorage() {
var helloVar = 'Hello, I am passed to PHP #1';
var worldVar = 'I am the second value passed to PHP!';
var processId = 'process_div';
var resultId = 'result_div';
var queryString = 'http://www.mysite.com/process.php?hello=' + helloVar + '&world=' + worldVar;
processAjax(queryString, processId, resultId);
}
次に、いくつかの HTML について説明します。
<div id="content">
<div id="process_div"> This is where processing will occur </div>
<div id="result_div"> This is where my response will display </div>
</div>
次に、process.php を作成します (注: セキュリティのため、JAVASCRIPT でサーバー側の処理ページを公開しないことを強くお勧めします)
<?php
//init
$hello = '';
$world = '';
$errors = 0;
//set
//Security note: never trust a URL request.. you should clean all $_GET, $_REQUEST, AND $_POST with the PHP htmlspecialchars() method (take a look at php.net for that)
(isset($_GET['hello'])) ? $hello = $_GET['hello'] : $errors++;
(isset($_GET['world'])) ? $world = $_GET['world'] : $errors++;
//process
if($errors > 0) {
echo 'Errors Detected! Missing querystring get data!';
} else {
echo '<p>Hello received: ' . $hello . '</p>';
echo '<p>World received: ' . $world . '</p>';
//now we can process $hello and $world server side!
}
?>
重要: 一部の JSON および $_POST リクエストについては、より安全で高速であり、返されたデータを簡単に操作できるため、実際に学習する必要があります。簡単な例については、jquery などのライブラリを参照することをお勧めします。
私はこのコードをテストしていませんが、うまくいくはずです。
喜んでお手伝いします!