无法正确接收服务器响应

时间:2018-08-17 16:21:26

标签: html node.js rest button

    <html>
        <form class="Headerformsearch" action="" method="">
            <div class = "SearchItem">
                <div class="input-group">
                    <input type="text" id="formcontrol" aria-label="..." placeholder="Search for products,brands and more">
                </div>
            </div>

            <div class = 'searchicon'>
                <button id = "search" type = 'submit' onclick="getDataFromServer()">
                    <i class="glyphicon glyphicon-search"></i>
                </button>
        </div>
        </form>

        <div id  = 'MyImg'>a</div>


        <style>
            .formcontrol{
                width:500px;
                height: 35px;
                border-radius: 2px;
                border-color: blue;

            }


            #search{
                width:50px;
                height: 36px;
                background-color: white;
            }
        </style>


        <script>
            var a;
            function getDataFromServer(){
            var data =   document.getElementById("formcontrol");

            var request = new XMLHttpRequest();
            request.responseType = 'text';
            request.open('GET', "http://localhost:8080/?" + data.value, true);
            request.onload = function () {
                timeout = 0;
                while((!(request.status >= 200 && request.status < 400)) && (!(timeout== 10000))){
                    setTimeout(function() {
                    timeout = timeout + 1000;  
                    }, 1000);
                }
                if (timeout== 10000){
                    console.error("connection not established with the server");
                }
                else{
                    var MyObj = JSON.parse(request.responseText);
                    document.getElementById("MyImg").innerHTML = 
                   MyObj.Title1;
                }


            }
            request.send();

            } 
       </script>
</html>

在上面的代码片段中,我试图使用REST API来获取Node js服务器响应。我从服务器端返回一个JSON并将其值显示在html页面中,但有时我无法从服务器,然后单击其中包含值的搜索按钮,占位符将重置为null响应。这里发生了什么问题?

0 个答案:

没有答案