'您必须记住,服务器端 (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 这样的库以获取简化示例。
我没有测试过这段代码,但它应该可以工作。如果你有问题或者这不能回答你的问题,请告诉我。
乐意效劳!