ajax上传js变量给php,AJAX / LocalStorage:是否可以将JS变量传递给PHP?

  • Post author:
  • Post category:php


‘您必须记住,在将代码转换为浏览器端代码之前,会读取服务器端(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 = ‘
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:

This is where processing will occur
This is where my response will display

现在有一个process.php(注意:为安全起见,我强烈建议你不要在你的JAVASCRIPT中显示服务器端处理页面)

//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 ‘

Hello received: ‘ . $hello . ‘

‘;

echo ‘

World received: ‘ . $world . ‘

‘;

//now we can process $hello and $world server side!

}

>

重要提示:您应该学习一些JSON和$ _POST请求,因为它们更安全,更快,您可以轻松地操作返回的数据。我建议查看像jquery这样的库来简化示例。

我没有测试过这段代码,但它应该可以运行..如果您有任何问题或者这不能回答您的问题,请告诉我。

很高兴帮忙!