通过 ajax 将参数传递给请求并使用 php 打印它
Passing parameter to request via ajax and printing it with php
我的 index.php:
<script type="text/javascript">
var chosenCity = 'London';
(function($) {
var formData = new FormData();
formData.append("city", chosenCity);
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php");
xhr.send(formData);
})(jQuery);
</script>
我想在我的页面中打印 chosenCity 的值,所以我这样做:
<?php
$var = $_REQUEST['city'];
echo $var;
print_r($_POST);
print_r($_REQUEST);
?>
但没有打印任何内容。
使用 php 调试器,在第一个调试会话中,我可以看到 $var 在第一次加载时包含 null。
并且在第二个调试会话中 $var
包含 'London'
... 然而即使在第二个会话之后也没有打印任何内容。
尝试打印 $_POST
和 $_REQUEST
时也会发生同样的情况
我尝试过不同的环境和浏览器
我做错了什么?
还有其他方法吗?
暂时忽略 jQuery 以下工作正常,这表明您用于发送 XHR 请求的 javascript 代码本身没有问题。
<?php
/*
"/test/target.php" ~ equivilent of index.php
*/
ob_clean();
print_r($_POST);
exit();
?>
function _ajax( chosenCity ){
var fd = new FormData();
fd.append('city', chosenCity);
fd.append('section','baselevel');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ) console.info( 'Response: %s',xhr.response );
};
xhr.open( 'POST', '/test/target.php' );
xhr.send( fd );
}
document.addEventListener( 'DOMContentLoaded', function(){ _ajax.call(this,'london') }, false );
我的 index.php:
<script type="text/javascript">
var chosenCity = 'London';
(function($) {
var formData = new FormData();
formData.append("city", chosenCity);
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php");
xhr.send(formData);
})(jQuery);
</script>
我想在我的页面中打印 chosenCity 的值,所以我这样做:
<?php
$var = $_REQUEST['city'];
echo $var;
print_r($_POST);
print_r($_REQUEST);
?>
但没有打印任何内容。
使用 php 调试器,在第一个调试会话中,我可以看到 $var 在第一次加载时包含 null。
并且在第二个调试会话中 $var
包含 'London'
... 然而即使在第二个会话之后也没有打印任何内容。
尝试打印 $_POST
和 $_REQUEST
我尝试过不同的环境和浏览器
我做错了什么?
还有其他方法吗?
暂时忽略 jQuery 以下工作正常,这表明您用于发送 XHR 请求的 javascript 代码本身没有问题。
<?php
/*
"/test/target.php" ~ equivilent of index.php
*/
ob_clean();
print_r($_POST);
exit();
?>
function _ajax( chosenCity ){
var fd = new FormData();
fd.append('city', chosenCity);
fd.append('section','baselevel');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ) console.info( 'Response: %s',xhr.response );
};
xhr.open( 'POST', '/test/target.php' );
xhr.send( fd );
}
document.addEventListener( 'DOMContentLoaded', function(){ _ajax.call(this,'london') }, false );