-2

ボタンをクリックするだけでAJAXリクエストを起動したいのですが、バックエンドでトリガーできません。

index.php

<html>
    <head>
        <script type="text/javascript">
            var req = new XMLHttpRequest();
            function send1()
            {
                req.open("GET", "process.php?q=hello", true);
                req.send();         
                alert(req.responseText);      
            }
        </script>
    </head>    

    <button onclick=send1()>send</button>

</html>

process.php

<?php
$new= $_GET['q'];
echo $new;
?>

これにより、アラートボックスに「こんにちは」と表示されるはずです。なぜそうではないのですか?

4

1 に答える 1

7

AJAXの最初のAは「非同期」を意味します。あなたがする必要があるのは、readyStateが変化するのを聞くことです:

req.open(...);
req.onreadystatechange = function() {
    if( this.readyState == 4) {
        if( this.status == 200) alert(this.responseText);
        else alert("HTTP error "+this.status+" "+this.statusText);
    }
};
req.send();
于 2012-07-28T16:46:56.753 に答える