Javascript 如何通过ajax传递全局变量
我有三个文件:Javascript 如何通过ajax传递全局变量,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我有三个文件: index.php ajax.php function.php 我想通过ajax.php将一个全局变量从index.php传递到function.php。 因此index.php中的警报消息应该是“2”。但事实上,结果是“1”,因为function.php不知道$global\u变量 代码如下: index.php <?php $global_variable = 1; ?> <script src="http://code.jquery.com/jquery-
index.php
ajax.php
function.php
我想通过ajax.php
将一个全局变量从index.php
传递到function.php
。
因此index.php
中的警报消息应该是“2”。但事实上,结果是“1”,因为function.php
不知道$global\u变量
代码如下:
index.php
<?php
$global_variable = 1;
?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'ajax.php',
success: function(data) {
alert(data);
}
});
</script>
<?php
include 'function.php';
$result = process_my_variable(1);
echo $result;
?>
<?php
function process_my_variable($new_variable) {
global $global_variable;
$result = $global_variable + $new_variable;
return $result;
}
?>
$.ajax({
类型:“POST”,
url:'ajax.php',
成功:功能(数据){
警报(数据);
}
});
ajax.php
<?php
$global_variable = 1;
?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'ajax.php',
success: function(data) {
alert(data);
}
});
</script>
<?php
include 'function.php';
$result = process_my_variable(1);
echo $result;
?>
<?php
function process_my_variable($new_variable) {
global $global_variable;
$result = $global_variable + $new_variable;
return $result;
}
?>
function.php
<?php
$global_variable = 1;
?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'ajax.php',
success: function(data) {
alert(data);
}
});
</script>
<?php
include 'function.php';
$result = process_my_variable(1);
echo $result;
?>
<?php
function process_my_variable($new_variable) {
global $global_variable;
$result = $global_variable + $new_variable;
return $result;
}
?>
我不想将全局变量传递给ajax调用,因为我的实际项目中有许多这样的变量,并且由于安全性的原因,它们不应该显示
如何做到这一点?$.ajax({
$.ajax({
type: "POST",
url: 'ajax.php',
data:{
global_variable:<?php echo $global_variable?>
},
success: function(data) {
alert(data);
}
});
类型:“POST”,
url:'ajax.php',
数据:{
全局变量:
},
成功:功能(数据){
警报(数据);
}
});
您可以将它与数据对象一起发送到ajax.php页面
在ajax.php页面,您可以通过以下方式获取它:
<?php
include 'function.php';
$global_var=$_POST['global_variable'];
$result = process_my_variable($global_var);
echo $result;
?>
index.php
和ajax.php
(附带函数.php
)是不同的程序。它们不共享变量
您需要将数据存储在两个程序都可以获取的地方(例如在会话中),或者将数据从index.php
传递到浏览器,然后将其发送到ajax请求的查询字符串或POST正文中的ajax.php