为什么这个ajax脚本不会使用ajaxRequest.open调用后端php?

时间:2012-11-07 23:12:16

标签: php javascript html ajax

<html><head><title>Loses</title></head><body>

<script language="javascript" type="text/javascript">
function ajaxFunction() {
    var ajaxRequest;
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    }catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    // Receive data from the server to update div
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var ajaxDisplay = document.getElementById('ajaxDiv');
            ajaxDisplay.value = ajaxRequest.responseText;
        }
    }

    // Get the value from user.
    if (!target) target = document.getElementById("name");
    var queryString = "?name=" + escape(target.value);

    var url = "db.php" + queryString;

    ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null); 
}
</script>

<form name="myForm">
    Victim: <input type="text" id="name" name="name"/> <br/>
    <br/>
    <input type="button" onclick="getLoses()" value="Show Loses"/>
</form>

<div id="ajaxDiv">Results:</div>
<br>

</body></html>

为什么不这样做?

我在apache和lightpd下试过了。我没有抱怨或错误,但它没有做任何事情。

如果我手动调用后端,db.php?name = Player1就可以了。所以它在db.php中不能是任何东西。上面的代码有问题,我只是不知道缺少什么。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

  1. 按钮单击调用函数getLoses(),但没有这样的函数(名称是ajaxFunction)
  2. if (!target) target = document.getElementById("name");

    没有变量目标,因此检查!target将导致脚本错误 从该行中删除if(!target)或将条件更改为:

    if (typeof target=='undefined' || !target)