【问题标题】:How to get the response from node.js server using ajax.get call如何使用 ajax.get 调用从 node.js 服务器获取响应
【发布时间】:2015-11-17 02:20:03
【问题描述】:

下面是来自 app.js 的代码 sn-p,它从 mongo.db 返回一个聚合值。我想在我的 html 页面中使用这个响应值。所以,我写了一个ajax调用。但是,问题是我无法将值放入 html 页面。我可以看到,我的服务器正在打印该值。

对服务器的 AJAX 调用:

$(suggestvalue).click(function (e) {
    var datapoint = document.getElementById('criteria').value;
    var criteriaVal = document.getElementById('condi').value;
    var datapoint_val = document.getElementById('rulevalue').value;
    var trigger_action = document.getElementById('actionvalue').value;
    $.ajax({
        url: "/suggestedValueTemp",
        type: 'GET',
        success: function (data) {
            alert("i am here");
            console.log(data);
        },
        error: function (e) {
            console.log(e.message);
        }
    });
});

app.get("/suggestedValueTemp",function(req,res){
    mongo.suggestTempValue(function(err,result){
        if(err){
            throw err;
        }else{
            console.log("avgTemp  "+result);
            res.send(result);
        }
    });
});

我在我的 console.logs 中得到了这个

avgTemp  35.17708659524805
[GET /suggestedValueTemp 35.17708659524805 2161ms ]

但它没有重新路由到我的 ajax 调用的成功块。谁能帮帮我。

谢谢, 湿婆神

【问题讨论】:

  • 是否触发了错误回调?另外,您是否尝试过在发送前设置响应码?
  • 哪个console.log() 语句正在生成您显示的控制台输出?
  • console.log in app.get 给了我这些输出
  • 您在浏览器控制台中看到了什么?
  • 如果您在浏览器的地址中输入 url 会发生什么...即http://whatever-your-host-is/suggestedValueTemp

标签: javascript ajax node.js mongodb


【解决方案1】:

在您的服务器端代码中试试这个。将res.send 更改为res.jsonp 并将对象传递给它。

app.get("/suggestedValueTemp",function(req,res){
    mongo.suggestTempValue(function(err,result){
        if(err){
            throw err;
        }else{
            console.log("avgTemp  "+result);
            res.jsonp({data: result}); //extract the data at user end
        }
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多