简体   繁体   English

JS loadResponse不起作用

[英]JS loadResponse doesnt work

I am building a basic calculator using JavaScript. 我正在使用JavaScript构建基本的计算器。

<script>
    function loadResponse(x){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("resultDiv").innerHTML = xmlhttp.responseText;  
            }
        }
        var uri = "http://localhost:8080/REST_service/rest/calculator/";
        switch(x){
            case 1:
                uri += "add/";
                break;

            case 2:
                uri += "subtract/";
                break;

            case 3:
                uri += "multiply/";
                break;

            case 4:
                uri += "divide/";
                break;
            default:
                break;
        }

        uri += document.getElementsByName("num1").value + "/" +
                    document.getElementsByName("num2");
        console.log(uri);
        xmlhttp.open("POST", uri, true);
        xmlhttp.send();
    }
</script>
<body>
        Number 1: <input type="text" name="num1" />
        Number 2: <input type="text" name="num2" />
        <input type="button" onclick="loadResponse(1)" value="ADD" />
        <input type="button" onclick="loadResponse(2)" value="SUBTRACT" />
        <input type="button" onclick="loadResponse(3)" value="MULTIPLY" />
        <input type="button" onclick="loadResponse(4)" value="DIVIDE" />

    <div id="resultDiv"></div>
</body>

But the console.log doesnt work, so the function is not getting called. 但是console.log无法正常工作,因此不会调用该函数。

What am I doing wrong? 我究竟做错了什么? How can I improve this code- calling loadResponse in a better way and also sending the values across to server side? 如何更好地改进此代码调用loadResponse并将值发送到服务器端?

Thanks 谢谢

This line is wrong: 这行是错误的:

    uri += document.getElementsByName("num1").value + "/" +
                document.getElementsByName("num2");

getElementsByName() returns a NodeList , so you need to index it to access the value. getElementsByName()返回一个NodeList ,因此您需要对其进行索引以访问该值。 And you didn't use .value for the second field. 而且您没有在第二个字段中使用.value It should be: 它应该是:

    uri += document.getElementsByName("num1")[0].value + "/" +
                document.getElementsByName("num2")[0].value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM