【问题标题】:Unable to pass response value from nodejs server to ajax function无法将响应值从 nodejs 服务器传递到 ajax 函数
【发布时间】:2018-05-18 15:24:38
【问题描述】:

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

我的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>

【问题讨论】:

  • 什么错误?附上它
  • process() 函数用于在我的 router.get 方法中传递输入字段的值。如果我删除括号它不起作用。错误是内部服务器错误。
  • setTimeout('process()', 1000000); - 这会尝试执行字符串,您可能需要将其更改为 setTimeout(process, 1000000);
  • 伙计,nodejs中没有DOMParser stackoverflow.com/questions/11398419/…
  • 如何将字符串从 router.get 方法传递给 handleServerResponse() 函数???

标签: javascript node.js ajax


【解决方案1】:

需要在router.get()函数末尾添加res.send(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2017-09-15
    • 1970-01-01
    • 2017-11-16
    • 2020-07-23
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多