jQuery Ajax在post中发送旧/旧数据

时间:2017-05-16 19:28:22

标签: javascript jquery ajax

假设我在JsonInput First中发送了一个这个JSON字符串:

{
"JobNumber": ["208-01"],
"Location": ["003118"],
"HostName": "TestHOST",
"WoNumber": "4268-6"
}

Ajax响应按预期成功完成。 如果我发送另一个请求:

{
 "JobNumber": ["208-01"],
 "Location": ["002365"],
 "HostName": "TestHOST",
 "WoNumber": "4268-6"
}

发送第一个请求,然后发送第二个请求。我想清除/销毁/清空任何先前的请求,它看起来像从第一个到第二个循环。我尝试使用sessionStorage.clear()得到相同的结果。

 $('#WorkOrders').on('change', function () {

    var WoValue = this.value;

    //Fade Out Section
    $('#topTable').fadeOut("slow");


    var Url = "/Shipping/api/WorkOrder/" + WoValue.substring(0, 6)


    $.getJSON(Url, function (data) {
        if (data.length === 0) {

            // New Method for WO info //4140-8
            $('.modal-body').empty();
            $('.modal-body').append("<p> No Data for " + WoValue + "</p>");
            $('#Modal').modal('show')

        } else {

            popHeader(data, WoValue);

            loadDataTable(WoValue);
        }

    });
});

popHeader功能

function popHeader(data, WoValue) {

    //Empty Header Contents
    $("#WoHeader").delay(2000).empty();
    $("#WoDetailLeft").delay(2000).empty();
    $("#WoDetailRight").delay(2000).empty();

    //$("#WoDetailReturn").find("tr:gt(0)").remove();
    $("#WoHeader").append("<h1>" + data[0].Name + "</h1>");
    $("#WoHeader").append("<h3>Work Order: " + WoValue + "</h3>");
    $("#WoHeader").append("<h3>Job: " + data[0].Job + "</h3>");
    $("#WoHeader").append("<h3>Job Date: " + data[0].JobDate + "</h3>");
    if (data[0].Carrier === "FX") {
        var Carrier = "FedEx";
    } else if (data[0].Carrier === "UP") {
        var Carrier = "UPS";
    } else {
        var Carrier = "N/A";
    }
    $("#WoHeader").append("<h3>Carrier: " + Carrier + "</h3>");
    //  $("#WoDetailLeft").append("<h5>Job Name: " + data[0].Name + "</h5>");
    $("#WoDetailLeft").append("<h5>Shipped To Client: " + data[0].ShippedToClient + "</h5>");
    $("#WoDetailLeft").append("<h5>Estimated Arrival: " + data[0].EstimatedArrivalDate + "</h5>");
    //   $("#WoDetailRight").append("<h5>Job Date: " + data[0].JobDate + "</h5>");
    $("#WoDetailRight").append("<h5>Client Ship Return: " + data[0].ClientReturnDate + "</h5>");
    $("#WoDetailRight").append("<h5>Estimate Return " + data[0].EstimatedReturnDate + "</h5>");

    //Clear Table


  $("#WoDetail").find("tr:gt(0)").remove();
}

loadDataTable函数:

function loadDataTable(WoValue) {
    var events = $('#events');
    var rows_selected = [];

    var table = $('#WoDetail').DataTable({
        "destroy": true,

        dom: 'Bfrtip',
        buttons: [
                'copy', 'excel'
        ],
        ajax: {
            url: "/Shipping/api/WorkOrder/" + WoValue.substring(0, 6),
            dataSrc: ""
        },
        'columnDefs': [{
            'targets': 9,
            'searchable': false,
            'orderable': false,
            'width': '1%',
            'className': 'dt-body-center',
            'render': function (data, type, full, meta) {
                return '<input type="checkbox">';
            }
        }],
        columns: [
            { "data": "Location" },
            {
                "data": "TrackingNumberOut",
                "render": function (data, type, full, meta) {
                    return '<a href="https://www.fedex.com/apps/fedextrack/?tracknumbers=' + data + '" target="_blank">' + data + '</a>';
                }
            },
            { "data": "StatusOut" },
            { "data": "ShipOrReturnOut" },
            {
                "data": null,
                "defaultContent":
                    'SYSTEM'
            },
            {
                "data": "TrackingNumberIn",
                "render": function (data, type, full, meta) {
                    return '<a href="https://www.fedex.com/apps/fedextrack/?tracknumbers=' + data + '" target="_blank">' + data + '</a>';
                }
            },
            { "data": "StatusIn" },
            { "data": "ShipOrReturnIn" },
            { "data": "strStkColorDesc" }

        ],
        'order': [[1, 'asc']],
        'rowCallback': function (row, data, dataIndex) {
            // Get row ID
            var rowId = data[0];
            var JobId = data[0];

            // If row ID is in the list of selected row IDs
            if ($.inArray(rowId, rows_selected) !== -1) {
                $(row).find('input[type="checkbox"]').prop('checked', true);
                $(row).addClass('selected');
            }
        }

    });
    $('#WoDetail').removeClass("hidden");
    $('#WoDetail').addClass("display")

    $('#topTable').fadeIn("slow");
    $('#btnSubmit').css('margin-top', '10px');
    $('#btnSubmit').removeClass("hidden");

    $('#WoDetail tbody').on('click', 'input[type="checkbox"]', function (e) {
        var $row = $(this).closest('tr');

        // Get row data
        var dataRow = table.row($row).data();

        // Get Location #

        var rowId = dataRow.Job + ":" + dataRow.Location;


        // Determine whether row ID is in the list of selected row IDs
        var index = $.inArray(rowId, rows_selected);


        // If checkbox is checked and row ID is not in list of selected row IDs
        if (this.checked && index === -1) {
            rows_selected.push(rowId);

            // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
        } else if (!this.checked && index !== -1) {
            rows_selected.splice(index, 1);
        }

        if (this.checked) {
            $row.addClass('selected');
        } else {
            $row.removeClass('selected');
        }

        // Update state of "Select all" control
        updateDataTableSelectAllCtrl(table);

        // Prevent click event from propagating to parent
        e.stopPropagation();
    });

    // Handle click on table cells with checkboxes
    $('#WoDetail').on('click', 'tbody td, thead th:first-child', function (e) {
        $(this).parent().find('input[type="checkbox"]').trigger('click');
    });

    // Handle click on "Select all" control
    $('thead input[name="select_all"]', table.table().container()).on('click', function (e) {
        if (this.checked) {
            $('#WoDetail tbody input[type="checkbox"]:not(:checked)').trigger('click');
        } else {
            $('#WoDetail tbody input[type="checkbox"]:checked').trigger('click');
        }

        // Prevent click event from propagating to parent
        e.stopPropagation();
    });

    // Handle table draw event
    table.on('draw', function () {
        // Update state of "Select all" control
        updateDataTableSelectAllCtrl(table);
    });

    $('.modal-body').empty();
    $('.modal-body').append('<p> The Following Jobs & Locations have been Scheduled </p>');

    $('#btnSubmit').on('click', function (e) {
        var form = this;

        if (rows_selected.length === 0) {
            $('.modal-body-err').empty();
            $('.modal-body-err').append('</p>Please make a selection</p>');
            $('#Modal-err').modal('show');
            return;
        }

        var str;
        var res;
        var final = [];
        var JobNumbers = [];
        var Locations = [];

        // Iterate over all selected checkboxes
        for (var i = 0; i <= (rows_selected.length - 1) ; i++) {

            str = rows_selected[i];
            res = str.split(":");
            JobNumbers.push(res[0]);
            Locations.push(res[1]);
            final.push(res);

        }

        var hostName = "@System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName"
        var netAddress = "@ViewContext.HttpContext.Request.UserHostName"
        console.log(hostName);
        console.log(netAddress);

        var woNumber = WoValue.substring(0, 6);

        var JsonInput = JSON.stringify({
            JobNumber: JobNumbers,
            Location: Locations,
            HostName: hostName,
            WoNumber: woNumber
        });


        for (var i = 0; i < Locations.length; i++) {

            $('#PickupDT tbody').append('<tr><td>' + JobNumbers[0] + '</td><td>' + Locations[i] + '</td></tr>');

        }
        $('#pickupModal').modal('show');
        $('#pickupOk').on('click', function () {
            $("#pickupOk").fadeOut();

            $.ajax({
                type: "POST",
                url: "/Shipping/SavePickups",
                contentType: 'application/json',
                dataType: "json",
                data: JsonInput,

                success: handleData

            });

            function handleData(data) {
                $("#pickupOk").delay(6000).fadeIn();
                if (data.Success == "True") {

                    $('.pickupModal-body').append('<h2>' + data.Message + '</h2>');
                    $('#WoDetail tbody input[type="checkbox"]:checked').trigger('click');

                    setTimeout(function () {
                        sessionStorage.clear();
                        $('#PickupClose').trigger('click');
                        $(".pickupModal-body").find("tr:gt(0)").remove();
                        $(".pickupModal-body").children("h2").remove();

                    }, 2000);
                }
                else {
                    $('.pickupModal-body').append('<hr/><br/><p> Pickups Failed To Schedule</p>')
                    $('#pickupModal').modal('show');
                }
            }

        });
        $('#PickupClose').on('click', function () {
            $(".pickupModal-body").find("tr:gt(0)").remove();

        });

    });

} // END OF loadDataTable Function

1 个答案:

答案 0 :(得分:0)

这是$('#pickupOk').on('click', function () {});

的约束性问题

我使用了$('#pickupOk').unbind('click');

点击功能不断添加到最后一个功能上,没有这个解除绑定就不会停止。

http://api.jquery.com/unbind/