开发者

Result of XMLHttpRequest dissappears

I am trying my hand on PHP. And I've landed at the client-server connectivity.

Now I have a server-side script that applies random math to an x and a y value that it gets via an XMLHttpRequest:

<?php
    $farr = array(
        create_function('$x,$y', 'return "x + y = ".($x+$y);'),
        create_function('$x,$y', 'return "x - y = ".($x-$y);'),
        create_function('$x,$y', 'return "x * y = ".($x*$y);'),
        create_function('$x,$y', '$returnVal = "x / y = "; if($y==0){$returnVal.="NaN (y value = 0)";}else{$returnVal.=($x/$y);}return $returnVal;')        
    );

    $x = $_GET["x"];
    $y = $_GET["y"];
    $i = rand(0,3);
    try{
        $f = $farr[$i];
        $result = $f($x,$y);
        echo "".$result;
    } catch(Exception $e) {
        echo "An exception occurred while accessing functions";
    }
?>

The client calls this script when a user presses the "Send" button on my form:

<html>
    <head>
        <title>
            Welcome
        </title>
        <script type="text/javascript">
            function calculate(x, y){
                var xmlhttp;
                if( x.length==0){
                    document.getElementById("result").innerHTML = "x is not set";
                    return;
                }
                if(y.length==0){
                    document.getElementById("result").innerHTML = "y is not set";
                    return;
                }
                if(window.XMLHttpRequest){
                    xmlhttp = new XMLHttpRequest();
                } else {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange=function(){
                    if(xmlhttp.readyState==4 && xmlhttp.status==200){
                        document.getElementById("result").innerHTML = xmlhttp.responseText;
                    }
                }
                xmlhttp.open("GET", "math.php?x="+x+"&y="+y, true);
                xmlhttp.send(null);
            }
        </script>
    </head>
    <body>
        <form>
            x: <input type="text" name="x"/><br/>
            y: <input type="text" name="y"/><br/>
            <input type="submit" value="Send" on开发者_如何学Cclick="calculate(x.value, y.value)"/> <input type="reset" value="Reset"/>
            <p>Result: <div id="result">something</div></p>
        </form>
    </body>
</html>

It is intended that the result is placed in the div at the end of the form. However, I see the result for a brief amount of time, and then it's gone again. I suspect the page from reloading, but isn't that the purpose of the XMLHttpRequest, that only the part in the onreadystatechanged callback get's refreshed? And not the whole page?


that's because you are using a submit button.. change

<input type="submit" to <input type="button"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜