簡體   English   中英

JavaScript到jQuery Ajax請求

[英]Javascript to jquery Ajax request

我有一些使用AjaxTomcat服務器發出請求的Javascript 我在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 servelet發出請求的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 ,但是我No 'Access-Control-Allow-Origin' header is present on the requested resource錯誤和我的Jquery Ajax請求的POST錯誤中No 'Access-Control-Allow-Origin' header is present on the requested resource Javscript No 'Access-Control-Allow-Origin' header is present on the requested resource

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

我是JqueryJavascript的新手,看不到我出了問題,研究向我建議,將crossDomain: true添加到Ajax Jquery請求中會在請求中設置標頭,所以也許我的代碼是問題?

編輯

再看看這個,已經是使用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);
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM