简体   繁体   中英

Javascript to jquery Ajax request

I have some Javascript that's using Ajax to make a request to my Tomcat server. I have a filter setup up on the Tomcat server to allow cross domain requests using:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

This is the Javascript snippet that I have successfully making request to my Tomcat servelet:

$(function() {

// Set the default dates
var startDate = Date.create().addDays(-6), // 7 days ago
endDate = Date.create(); // today

var range = $('#range');

// Show the dates in the range input
range.val(startDate.format('{MM}/{dd}/{yyyy}') + ' - '
        + endDate.format('{MM}/{dd}/{yyyy}'));

// Load chart
ajaxLoadChart(startDate, endDate);

range.daterangepicker({
    startDate : startDate,
    endDate : endDate,
    ranges : {
        'Today' : [ 'today', 'today' ],
        'Yesterday' : [ 'yesterday', 'yesterday' ],
        'Last 7 Days' : [ Date.create().addDays(-6), 'today' ],
        'Last 30 Days' : [ Date.create().addDays(-29), 'today' ]
    }
}, function(start, end) {
    ajaxLoadChart(start, end);
});

// Function for loading data via AJAX and showing it on the chart
function ajaxLoadChart(startDate, endDate) {
    // If no data is passed (the chart was cleared)
    if (!startDate || !endDate) {
        return;
    }
    // Otherwise, issue an AJAX request
    $.post('http://192.168.1.6:8083/Servlet/PreProcessor', {
        start : startDate.format('{MM}/{dd}/{yyyy}'),
        end : endDate.format('{MM}/{dd}/{yyyy}')
    }, function(data) {
        if ((data.indexOf("No record found") > -1)
                || (data.indexOf("Date must be selected.") > -1)) {
            $('#msg').html('<span style="color:red;">' + data + '</span>');
        } else {
            $('#msg').empty();
            $('#chart').highcharts({
                chart : {
                    type : 'arearange',
                    zoomType : 'x'
                },

                title : {
                    text : 'Temperature variation by day'
                },

                xAxis : {
                    type : 'datetime'
                },

                yAxis : {
                    title : {
                        text : null
                    }
                },

                tooltip : {
                    crosshairs : true,
                    shared : true,
                    valueSuffix : '°C'
                },

                legend : {
                    enabled : false
                },

                series : [ {
                    name : 'Temperatures',
                    data : data
                } ]
            });
        }
    }, 'json');
    }
});

I'm trying to convert the Javscript Ajax request to Jquery , but I'm getting a No 'Access-Control-Allow-Origin' header is present on the requested resource error and a POST error with my Jquery Ajax request:

$(function () {

// Set the default dates
var startDate = Date.create().addDays(-6), // 7 days ago
endDate = Date.create(); // today

var range = $('#range');

// Show the dates in the range input
range.val(startDate.format('{MM}/{dd}/{yyyy}') + ' - '
        + endDate.format('{MM}/{dd}/{yyyy}'));

// Load chart
ajaxLoadChart(startDate, endDate);

range.daterangepicker({
    startDate: startDate,
    endDate: endDate,
    ranges: {
        'Today': ['today', 'today'],
        'Yesterday': ['yesterday', 'yesterday'],
        'Last 7 Days': [Date.create().addDays(-6), 'today'],
        'Last 30 Days': [Date.create().addDays(-29), 'today']
    }
}, function (start, end) {
    ajaxLoadChart(start, end);
});

// Function for loading data via AJAX and showing it on the chart
function ajaxLoadChart(startDate, endDate) {
    // If no data is passed (the chart was cleared)
    if (!startDate || !endDate) {
        return;
    }


     // Otherwise, issue an AJAX request
        $.ajax({
            url: 'http://192.168.1.6:8083/Servlet/PreProcessor',
            type: 'POST',
            crossDomain: true,
            async: true,
            dataType: "json",
            start: startDate.format('{MM}/{dd}/{yyyy}'),
            end: endDate.format('{MM}/{dd}/{yyyy}'),
            success: function (data) {
                defaultChart(data);
            }
        });
    }
});


function defaultChart(data) {
    if ((data.indexOf("No record found") > -1)
                     || (data.indexOf("Date must be selected.") > -1)) {
        $('#msg').html('<span style="color:red;">' + data + '</span>');
    } else {
        $('#msg').empty();
        $('#chart').highcharts({
            chart: {
            type: 'arearange',
            zoomType: 'x'
        },

        title: {
            text: 'Temperature variation by day'
        },

        xAxis: {
            type: 'datetime'
        },

        yAxis: {
            title: {
                text: null
            }
        },

        tooltip: {
            crosshairs: true,
            shared: true,
            valueSuffix: '°C'
        },

        legend: {
            enabled: false
        },

        series: [{
            name: 'Temperatures',
            data: data
        }]
    });
    }
}

I'm a novice with both Jquery and Javascript and can't see where I've gone wrong, research suggested to me that adding crossDomain: true to the Ajax Jquery request would set the header in the request, so maybe my code is the problem?

EDIT

Looking at this again is the first snippet using Jquery already?

The first code snippet is using jQuery. $Post syntactic sugar for using $.ajax with type="POST". I'm not sure why you would get a CORS error with the second code, but not the first. You can troubleshoot the headers using chrome developer tools to look the headers on the requests and responses.
Alternatively, if you are posting to the same url, you can use a relative address instead of a fully qualified HTTP:// address.

So the problem with my code was the way that you add parameters to the Ajax request

My entail attempt was structured like so:

$.ajax({
        url: 'http://192.168.1.6:8083/Servlet/PreProcessor',
        type: 'POST',
        crossDomain: true,
        async: true,
        dataType: "json",
        start: startDate.format('{MM}/{dd}/{yyyy}'),
        end: endDate.format('{MM}/{dd}/{yyyy}'),
        success: function (data) {
            defaultChart(data);
        }
    });

When it should have been structured like this:

$.ajax({
        url: 'http://192.168.1.6:8083/IBMServlet_war/PreProcessor',
        crossDomain: true,
        async: true,
        type: "POST",
        dataType: "json",
        data:{ start: startDate.format('{MM}/{dd}/{yyyy}'), end : endDate.format('{MM}/{dd}/{yyyy}')},
        success: function (data) {
            defaultChart(data);
        }
    }).error(function(xhr, status, error) {
            alert("error");
            console.log(xhr);
    });

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