Javascript to jquery Ajax request

Javascript to jquery Ajax request

本文关键字:request Ajax jquery to Javascript      更新时间:2023-09-26

我有一些Javascript正在使用Ajax向我的Tomcat服务器发出请求。我在Tomcat服务器上设置了一个过滤器,以允许使用以下方法进行跨域请求:

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

这是我成功向我的Tomcat servlet 发出请求的Javascript片段:

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

我正在尝试将Javscript Ajax请求转换为Jquery,但是我的Jquery Ajax请求出现No 'Access-Control-Allow-Origin' header is present on the requested resource错误和POST错误:

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

我是一个新手,既有Jquery又有Javascript,看不到我哪里出错了,研究表明,向 Ajax Jquery 请求添加crossDomain: true会在请求中设置标头,所以也许我的代码是问题所在?

编辑

再看这个是第一个使用 Jquery 的代码片段吗?

第一个代码片段是使用 jQuery。 $Post 将 $.ajax 与 type="POST" 一起使用的语法糖。我不确定为什么第二个代码会出现 CORS 错误,而不是第一个代码。您可以使用 chrome 开发者工具排查标头问题,以查看请求和响应中的标头。
或者,如果要发布到同一 URL,则可以使用相对地址而不是完全限定的 HTTP://地址。

所以我的代码的问题在于你向Ajax请求添加参数的方式

我的必然尝试结构如下:

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

当它应该像这样构建时:

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