0

我正在尝试使用 ajax 将一些变量发送到 php 页面,然后在 div 中显示它们,但它不起作用。

html代码:

<div id="center">
    <form>                                  
        <input type="text" id="toSearch" class="inputText" title="Search for ...">              
        <select name="thelist1" id="ecoElem" class="comboBox">
            <option>-- Ecosystem Element --</option>
        </select> 
        <select name="thelist2" id="ecoActor" class="comboBox">                         
            <option>-- Ecosystem Actor --</option>
        </select>   
        <input type="button" value="Search" id="searchButton" onclick="loadData();">
    </form>        
</div>
 <div id="resBox">
    </div>

加载数据函数:

function loadData(){
            if(window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
            }
            else{
                xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
            }

            searchT = document.getElementById('toSearch').value;
            ecoElem = document.getElementById('ecoElem').value;
            ecoActor = document.getElementById('ecoActor').value;

            xmlhttp.onreadystatechange = function(){
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    document.getElementById('resBox').innerHTML = xmlhttp.responseText;
                }
            }

            xmlhttp.open("POST","databaseRead.php",true);
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlhttp.send("text=" + searchT + "&elem=" + ecoElem + "&actor=" + ecoActor);}

最后是 php 页面:

<?php   
$searchT = $_POST['text'];
$ecoElem = $_POST['elem'];
$ecoActor = $_POST['actor'];
echo $searchT;
?>

就是这样,我已经为此工作了几个小时,但仍然无法弄清楚。

4

2 回答 2

0

您也可以使用 JQuery。

function loadData(){   
     var searchT = $('#toSearch').val(); 
     var toSearch = $('#ecoActor ').val();    
     var ecoActor = $('#ecoActor').val();
     $.post("databaseRead.php"),{ text:searchT, elem:toSearch, actor:ecoActor },
          function(data){
          $('#resBox').html(data);
     });
}
于 2012-06-13T17:50:56.623 回答
0

尝试更改按钮,使 onclick 返回 false(以防提交表单)...

<input type="button" value="Search" id="searchButton" onclick="loadData();return false;">

此外,您可能希望对文本框中的值进行 URL 编码,否则有人输入 = 或 & 会搞砸一切......

xmlhttp.send("text=" + encodeURIComponent(searchT) + "&elem=" + + encodeURIComponent(ecoElem) + "&actor=" + + encodeURIComponent(ecoActor));}
于 2012-06-13T14:23:29.487 回答