简体   繁体   English

在ajax中发布php变量(无jQuery)

[英]post php variable in ajax (no jQuery)

I guess this is simple question, but not for me. 我想这是一个简单的问题,但对我来说不是。 I have got simple calendar, where is only month: 我有简单的日历,只有一个月:

<div id="calendar">
<?php
$month_num=date('m');
echo $month_num . " ";
echo '<span onclick="next(this.value);" value="' . $month_num . '";> &gt; </span>';
?>
</div>

my script is: 我的脚本是:

function next(str) {

xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
   document.getElementById("calendar").innerHTML = this.responseText;
   }
};
xmlhttp.open("POST","test3.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("n=" + str);
}

and test3.php is: test3.php是:

<?php
if (isset($_POST['n'])) {
    $n = $_POST['n'];
}
if (isset($n)) { 
    echo $n + 1;} 
?>

Problem is, $n is undefined and result is "1" . 问题是, $n是未定义的,结果是“ 1”。 I guess there should be some nice simple way how to post $n . 我猜应该有一些简单的方法发布$n

Thank you. 谢谢。

A span does not have a value attribute according to specifications. 根据规格,跨度没有值属性。 So you will have a hard time access it in javascript. 因此,您将很难用javascript访问它。 Try using the data-* attributes for that. 尝试为此使用data- *属性。

echo '<span onclick="next(this.getAttribute(\'data-value\'));" data-value="' . $month_num . '";> &gt; </span>';

May I also suggest that, since you are posting, and relying on a click event, a button would be much more appropriate. 我也可以建议,由于您正在发布并且依赖于click事件,因此按钮会更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM