简体   繁体   中英

How to get the response from node.js server using ajax.get call

Below is the code snippet from app.js which returns a aggrgated value from mongo.db. I want to use this response value in my html page. So, I have written a ajax call. But, the problem is i'm not able to get the value into html page. I can see, that my server is printing the value.

AJAX call made to the server:

$(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);
        }
    });
});

I'm getting this in my console.logs

avgTemp  35.17708659524805
[GET /suggestedValueTemp 35.17708659524805 2161ms ]

but its not rerouting to success block of my ajax call. Can anybody please help me out.

Thanks, Shivadeepthi

Try this in your server side code. Change res.send to res.jsonp and pass an object to it.

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
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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