通过AJAX传输变量

时间:2016-05-16 13:22:23

标签: javascript php html ajax variables

我目前正在制作日程表。在日历旁边,我想要一个描述框,当用户点击日历中的日期时,应该显示有关该事件的更多信息。

到目前为止我所拥有的: HTML / PHP:

// Variables from MySQL request:    
$event
$date
$place
$start
$end

<button type="button" onclick="event_description()">$day</button>

<div id="details"></div>

AJAX:

function event_description() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("details").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "kalender/description.php", true);
  xhttp.send();
}

那么我能做什么呢?我可以在description.php中使用MySQL变量吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你可以使用这样的东西......

// Variables from MySQL request:        
$event
$date
$place

///pass all the parameters in onclick function as arguments 

<button type="button" onclick="event_description('<?php echo $event ?>','<?php echo $date ?>','<?php echo $place ?>')">$day</button>
<div id="details"></div>

脚本代码

<script>
///get all the params here in function
function event_description(event_name,date,place) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("details").innerHTML = xhttp.responseText;
    }
  };

  /////create a string of all the parameters and pass this with requested url as query string and get all these params in target file using `$_GET[]`

  var params = 'event_name='+event_name+'&date='+date+'&place='+place;
  xhttp.open("GET", "kalender/description.php?"+params, true);
  xhttp.send();
}
</script>