1

私は AJAX を学ぶのが初めてで、最初のプログラムで立ち往生しています。デバッグしようとしましたが、できませんでした。

以下は私のコードスニペットです

----------input-ajax.html-------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML PAGE</title>
<script type="text/javascript">
    var request=null;
    function createRequest(){
        try{
            request= new XMLHttpRequest();
        )catch(e){
            try{
                request=new ActiveXObject("Msxml2.XMLHTTP");
            }catch(e){
                try{
                    request= new ActiveXObject("Microsoft.XMLHTTP");
                }catch(failed){
                    request=null;
                }
            }
        }
        if(request==null){
            alert("Error Creating Request Object");
        }
    }
    function getName(){
        alert("getname called");
        createRequest();
        var url = "showName-ajax.jsp";
        request.open("POST",url,true);
        alert("before");
        request.onreadystatechange = updatePage;
        alert("after");
        request.send(null);
    }
    function updatePage(){
        //var newName= request.getResponseHeader("r1");
        var newName= request.responseText;
        var name1 = document.getElementById("name");
        replaceText(name1,newName);
    }
    function replaceText(el, text) {
          if (el != null) {
            clearText(el);
            var newNode = document.createTextNode(text);
            el.appendChild(newNode);
          }
    }

    function clearText(el) {
        if (el != null) {
            if (el.childNodes) {
              for (var i = 0; i < el.childNodes.length; i++) {
                var childNode = el.childNodes[i];
                el.removeChild(childNode);
              }
            }
        }
    }
</script>
</head>
<body>
<h1>WELCOME <span id="name"> GUEST</span></h1>
<form method="POST">
<input type="text" name="t1">
<input type="button" value="Show Name" onclick="getName();"/>
</form>
</body>
</html>

----------showName-ajax.jsp------------

<%
    String s1=request.getParameter("t1");
    response.setContentType("text/plain");  
    response.setCharacterEncoding("UTF-8"); 
    response.getWriter().write(s1);       // Write response body.
 %>

しかし、プログラムを実行しても (ボタンをクリックしても) 何も起こりません。getName 関数が呼び出されたという警告メッセージも表示されません。助けてください!!!!

4

3 に答える 3

0
change )catch(e){  to }catch(e){

しかし、なぜボタンクリックで毎回リクエストオブジェクトを作成するのですか?ページ読み込みイベントで「createRequest()」を1回だけ呼び出す必要があります。

于 2012-08-17T18:06:12.660 に答える
0

打ち間違え:

)catch(e){

する必要があります

}catch(e){

これは、ブラウザのコンソールにエラーとして表示されます。正常に動作しない場合は、必ず最初に確認してください。

于 2012-08-17T17:43:39.610 に答える
0

ここに } の代わりに ) があります。

try{
    request= new XMLHttpRequest();
)catch(e){

したがって、関数が定義されることはありません。

于 2012-08-17T17:43:55.020 に答える