Ajax在节点js中返回未定义的响应?

时间:2017-02-06 13:43:56

标签: javascript jquery ajax node.js

我正在尝试将ajax请求发布到节点js中的server.js脚本。然后,脚本将数据从ajax请求传递给存储过程,并且应该将结果返回给ajax函数。但由于某种原因,我在调试我的ajax函数时遇到了一个未定义的错误。我能做错什么?

plain.ejs

<html>
<head>

    <script src="http://code.jquery.com/jquery-1.11.3.min.js" ></script>
    <script src="http://code.highcharts.com/highcharts.js" ></script>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>


</head>
<body>
<div id="container1" style="width:100%; height:400px;"></div>
<div id ="container2" style="height:20px;"></div>
<div id ="container3" style="width:100%; height:400px;"></div>
<script type="text/javascript">



     $(document).ready(function () {
            var bankid = [ 57, 9912, 9905, 16, 58 ];
            var country = ["KENYA", "KENYA", "KENYA", "UGANDA", "UGANDA"];
            var counter = 0;
            var merchantname = [];
            var successtranscs = [];
            var failedtranscs = [];
            var servicetranscs = [];
            var bankname;
            var rows =<%-JSON.stringify(Resultset)%>

                function initfunc() {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/dashboard",
                        data: JSON.stringify({country: country[counter], bankid: bankid[counter]}),
                        dataType: "json",
                        success: function (Result) {
                            Result = Result.d;
                            console.log("result" +Result);
                            var data = [];
                            var merchantname = [];
                            var successtranscs = [];
                            var failedtranscs = [];
                            var servicetranscs = [];
                            var bankname;

                            for (var i in Result) {
                                merchantname.push(Result[i].merchant_name);
                                successtranscs.push(Result[i].success_transcs);
                                failedtranscs.push(Result[i].failed_transcs);
                                servicetranscs.push(Result[i].service_transcs);
                                bankname = Result[i].bankname;


                            }
                            StackedChart(bankname, merchantname, successtranscs, failedtranscs, servicetranscs);
                            merchantname = [];
                            successtranscs = [];
                            failedtranscs = [];
                            servicetranscs = [];
                            if (counter == country.length - 1) {
                                counter = -1;
                                counter++;
                            }
                            else {
                                counter++;
                            }
                        },
                        error: function (Result) {
                            console.log(Result.d);
                        }
                    });


            }
            initfunc();
            function callfunc() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/dashboard",
                    data: JSON.stringify({country: country[counter], bankid: bankid[counter]}),
                    dataType: "json",
                    success: function (Result) {
                        Result = Result.d;
                        console.log("result" +Result);
                        var data = [];
                        var merchantname = [];
                        var successtranscs = [];
                        var failedtranscs = [];
                        var servicetranscs = [];
                        var bankname;

                        for (var i in Result) {
                            merchantname.push(Result[i].merchant_name);
                            successtranscs.push(Result[i].success_transcs);
                            failedtranscs.push(Result[i].failed_transcs);
                            servicetranscs.push(Result[i].service_transcs);
                            bankname = Result[i].bankname;


                        }
                        StackedChart(bankname, merchantname, successtranscs, failedtranscs, servicetranscs);
                        merchantname = [];
                        successtranscs = [];
                        failedtranscs = [];
                        servicetranscs = [];
                        if (counter == country.length - 1) {
                            counter = -1;
                            counter++;
                        }
                        else {
                            counter++;
                        }
                    },
                    error: function (Result) {


 console.log(Result.d);//it keeps going to the error //function

                    }
                });


            }




            function StackedChart(bank_name,merch_name, succ_val, fail_val, ser_val) {

                var myChart = Highcharts.chart('container1', {
                    chart: {
                        type: 'column'
                    },
                    title: {
                        text: bank_name
                    },
                    xAxis: {
                        categories: merch_name
                    },
                    yAxis: {
                        min: 0,
                        title: {
                            text: 'TransactionStatus'
                        },
                        stackLabels: {
                            enabled: true,
                            style: {
                                fontWeight: 'bold',
                                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                            }
                        }
                    },
                    legend: {
                        align: 'right',
                        x: -30,
                        verticalAlign: 'top',
                        y: 25,
                        floating: true,
                        backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
                        borderColor: '#CCC',
                        borderWidth: 1,
                        shadow: false
                    },
                    tooltip: {
                        headerFormat: '<b>{point.x}</b><br/>',
                        pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
                    },
                    plotOptions: {
                        column: {
                            stacking: 'normal',
                            dataLabels: {
                                enabled: true,
                                color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
                            }
                        }
                    },
                    series: [{
                        name: 'Servicefailure',
                        data: ser_val
                    }, {
                        name: 'Failure',
                        data: fail_val
                    }, {
                        name: 'Success',
                        data: succ_val
                    }]
                });
            }




            setInterval(callfunc, 2000);
        });



</script>


</body>
</html>

server.js -

var express = require('express');
var cnn = require('./DbConnection.js');
var bodyParser = require('body-parser');
require('highcharts');
var app = express();
app.use(express.bodyParser());
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); //
app.engine('html', require('ejs').renderFile);
dirname = "C:/Users/user/WebstormProjects/untitled/public";

require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});
app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
});



app.get('/', function (req, res) {
    var obj;

    cnn.TransactionInfo("KENYA","57", function (err, result) {
        // process result here
         console.log(result.length);
        var resultset = {"Result":result};
       obj = { "title":"fruit consumption", "name":"fruit eaten"};

        res.render("plain.ejs",{Resultset:resultset});

    });



});
app.post('/dashboard', function (req, res) {
    cnn.TransactionInfo(req.body.country,req.body.bankid, function (err, result) {

        var resultset = {"Result":result};


        res.render("plain.ejs",{Resultset:resultset});

    });
});

1 个答案:

答案 0 :(得分:0)

通过指定dataType : "json",您告诉jQuery它应该期望服务器返回JSON数据。但是,您的Express处理程序正在发回HTML:

res.render("plain.ejs",{Resultset:resultset});

因此,错误可能是jQuery无法解码响应。

尝试发回JSON响应:

res.json({ Resultset : resultset });