使用ajax发送参数不起作用

时间:2012-06-13 14:09:55

标签: javascript html ajax

我正在尝试使用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>

loadData函数:

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;
?>

就是这样,我已经在这个问题上工作了几个小时,但仍然无法理解。

2 个答案:

答案 0 :(得分:0)

尝试更改按钮,以便onclick返回false(如果提交表单)...

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

此外,您可能希望对文本框中的值进行URL编码,否则有人会输入=或a&amp;会弄得一团糟......

xmlhttp.send("text=" + encodeURIComponent(searchT) + "&elem=" + + encodeURIComponent(ecoElem) + "&actor=" + + encodeURIComponent(ecoActor));}

答案 1 :(得分: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);
     });
}