将php变量添加到ajax中

时间:2017-06-15 10:49:46

标签: php ajax

如何在没有jQuery的情况下使用php变量? 我的test.php文件:

<?php 
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>    
<script>
function setCookie() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "setCookie.php", true);
  xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>

和我的setCookie.php文件是:

<?php
session_start();
$_SESSION['xxx'] = $language;
?>

如果我在setCookie.php中放入一些简单的echo语句,它就可以工作并出现在我的网站上。但为什么它不能为会话[&#39; xxx&#39;]分配$语言价值?

2 个答案:

答案 0 :(得分:0)

Beacuse ajax在调用时将是新请求,因此您必须使用它传递值。  试试这个:

<强> test.php的

<?php 
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>    
<script>
function setCookie() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
    language = '<?=$language?>'; //get value
  xhttp.open("POST", "setCookie.php", true); 
  xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send("language=" + language); //send as post params
  xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>

<强> setCookie.php

<?php
session_start();
$language = $_POST['language']; //retrive value
$_SESSION['xxx'] = $language; //assign to session
?>

答案 1 :(得分:0)

只需更改您的setCookie.php文件,如下所示。

<?php
session_start();
$_SESSION['xxx'] = $_POST['language'];
?>