经过多次研究,我推断如果我想将javascript变量传输到php函数,我需要使用AJAX请求。我读了一篇关于它的教程,我认为我已经有了很好的开始。然而,我不知道我接下来要做什么:如果有人能解释我的过程,我是(因为它是一个有点模糊),这将是非常感激!我是这样做的:
// encode the variables
dayInput = encodeURIComponent(dayInput);
monthInput = encodeURIComponent(monthInput);
yearInput = encodeURIComponent(yearInput);
// prepare the ajax request
var xhr = new XMLHttpRequest();
xhr.open('GET', 'createList.php?day=' + dayInput + '&month=' + monthInput + '&year=' + yearInput);
xhr.send(NULL);
xhr.onreadystatechange = function(){
if(xhr.readyState == xhr.DONE && xhr.status == 200)
{
//WHAT TO DO??
}
}
假设脚本返回HTML,您可以像这样将其插入DOM:
xhr.onreadystatechange = function(){
if(xhr.readyState == xhr.DONE && xhr.status == 200){
document.getElementById('listbox').innerHTML = xhr.responseText;
}
}
根据你想对php页面返回的数据做什么,你应该解析它成一个DOM元素,这样它就可以用JavaScript访问:
xhr.onreadystatechange = function(){
if(xhr.readyState == xhr.DONE && xhr.status == 200){
var parser = new DOMparser(),
doc = parser.parse(xhr.responseText, 'text/html');
// do something with doc, like:
var list = doc.getElementById('list');
document.getElementById('some-id').innerHTML = list;
}
}