无法将nodejs服务器的响应值传递给ajax函数

时间:2018-05-17 13:14:13

标签: javascript node.js ajax

我已将process()函数的数据发送到router.get方法。但我无法将xmlString方法的router.get变量传递给handleServerResponse() test.js.It中的方法显示内部服务器错误。请修复我的问题。提前谢谢。

我的test.js文件

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject(){
    var xmlHttp;

    if(window.ActiveXObject){
        try{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e){
            xmlHttp = false;
        }
    }else{
        try{
            xmlHttp = new XMLHttpRequest();
        }catch(e){
            xmlHttp = false;
        }
    }

    if(!xmlHttp){
        alert("Cant create that object");
    }else{
        return xmlHttp;
    }
}

function process(){
    if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
        var food = document.getElementById("userInput").value;
        console.log(food);

        xmlHttp.open("GET", "/start/" + food, true);
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send(null);
    } else {
        setTimeout('process()', 1000);
    }
}



function handleServerResponse(){
    let xmlResponse;
    let xmlDocumentElement;
    let message;
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {

            console.log("check done");
             xmlResponse = xmlHttp.responseXML;
             xmlDocumentElement = xmlResponse.documentElement;
             message = xmlDocumentElement.firstChild;
             console.log(message);
            document.getElementById("underInput").innerHTML = '<span style="color:blue"></span>';
            setTimeout('process()', 1000000);
        } else {
            alert('Something went wrong!');
        }
    }
}

我的index.js文件

router.get('/start/:id', function(req, res, next) {
    console.log(req.params.id);

    var xmlString = "<div id='foo'><a href='#'>Hello BigGo</a><span></span></div>"
        , parser = new DOMParser()
        , doc = parser.parseFromString(xmlString, "text/xml");
    var data='dip';
 });

我的add.hbs文件

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="test.js"></script>
</head>
<body >


<h3>The Chuff Bucket</h3>
Enter the foood you would like to order:
<input type="text" id="userInput" oninput="process()" />
<div id="underInput"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要在router.get()函数

的末尾添加res.send(data)
相关问题