在jQuery中发出Ajax请求时,事件只会触发一次 [英] Event only fires once when making Ajax request in jQuery

查看:91
本文介绍了在jQuery中发出Ajax请求时,事件只会触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个使用SPServices从SharePoint填充的下拉菜单。这部分效果很好。但是,我有一个按钮,点击加载来自SharePoint的数据,并使用下拉文本作为过滤器来获取将使用DataTables插件填充表的数据。这部分只工作一次;如果我再次点击该按钮,则没有任何反应。

I have a couple of drop downs that are populated from SharePoint using SPServices. This part works great. But then, I have a button that on click loads data from SharePoint and uses the dropdown texts as filter to fetch the data that will populate a table using the DataTables plugin. This part works only once; if I click the button again, nothing happens.

这就是我填充下拉列表的方式:

This is how I populate the dropdowns:

$(document).ready(function () {
var theYear; // Selected Year
var theRO; // Selected RO
//Fills the Dropdown lists (Year and RO)
$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "{ListID}",
    CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef    Name='Regional_x0020_Office' /></ViewFields>",
    completefunc: function (xData, Status) {
        //Add Select Value option
        $("#dropdown").prepend($('<option>', {
            value: '',
            text: 'Select Fiscal Year'
        }));
        $("#dropdownRO").prepend($('<option>', {
            value: '',
            text: 'Select Regional Office'
        }));
        //Fetching Data from SharePoint    
        $(xData.responseXML).SPFilterNode("z:row").each(function () {
            var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>";
            var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>";
            $("#dropdown").append(dropDown);
            $("#dropdownRO").append(dropDownRO);
            /////////////Deletes duplicates from dropdown list////////////////
            var usedNames = {};
            $("#dropdown > option, #dropdownRO > option").each(function () {
                if (usedNames[this.text]) {
                    $(this).remove();
                } else {
                    usedNames[this.text] = this.value;
                }
            });
            ////Deletes repeated rows from table
            var seen = {};
            $('#myTable tr, #tasksUL li, .dropdown-menu li').each(function () {
                var txt = $(this).text();
                if (seen[txt]) $(this).remove();
                else seen[txt] = true;
            });
        });
    } //end of completeFunc
}); //end of SPServices
$('.myButton').on('click', function () {
    run()
});
}); //End jQuery Function

这是我每次点击myButton时需要运行的函数在下拉菜单中更改我的选择后:

This is the function I need to run every time I click on "myButton" after changing my selection in the dropdowns:

        function run() {

theYear = $('#dropdown option:selected').text(); // Selected Year
theRO = $('#dropdownRO option:selected').text(); // Selected RO
var call = $.ajax({
    url: "https://blah-blah-blah/_api/web/lists/getByTitle('Consolidated%20LC%20Report')/items()?$filter=Fiscal_x0020_Year%20eq%20'" + theYear + "' and Regional_x0020_Office eq '" + theRO + "'&$orderby=Id&$select=Id,Title,Fiscal_x0020_Year,Notices_x0020_Received,Declined_x0020_Participation,Selected_x0020_Field_x0020_Revie,Selected_x0020_File_x0020_Review,Pending,Pending_x0020_Previous_x0020_Yea,Controversial,GFP_x0020_Reviews,NAD_x0020_Appeals,Mediation_x0020_Cases,Monthly_x0020_Cost_x0020_Savings,Monthly_x0020_Expenditure,Regional_x0020_Office,Month_Number", //Works, filters added
    type: "GET",
    cache: false,
    dataType: "json",
    headers: {
        Accept: "application/json;odata=verbose",
    }
}); //End of ajax function///
call.done(function (data, textStatus, jqXHR) {
    var oTable = $('#example').dataTable({
        "aLengthMenu": [
            [25, 50, 100, 200, -1],
            [25, 50, 100, 200, "All"]
        ],
            "iDisplayLength": -1, //Number of rows by default. -1 means All Records
        "sPaginationType": "full_numbers",
            "aaData": data.d.results,
            "bJQueryUI": false,
            "bProcessing": true,
            "aoColumns": [{
            "mData": "Id",
            "bVisible": false
        }, //Invisible column
        {
            "mData": "Title"
        }, {
            "mData": "Notices_x0020_Received"
        }, {
            "mData": "Declined_x0020_Participation"
        }, {
            "mData": "Selected_x0020_Field_x0020_Revie"
        }, {
            "mData": "Selected_x0020_File_x0020_Review"
        }, {
            "mData": "Pending"
        }, {
            "mData": "Pending_x0020_Previous_x0020_Yea"
        }, {
            "mData": "Controversial"
        }, {
            "mData": "GFP_x0020_Reviews"
        }, {
            "mData": "NAD_x0020_Appeals"
        }, {
            "mData": "Mediation_x0020_Cases"
        }, {
            "mData": "Monthly_x0020_Cost_x0020_Savings",
            "fnRender": function (obj, val) {
                return accounting.formatMoney(val);
            }
        }, {
            "mData": "Monthly_x0020_Expenditure",
            "fnRender": function (obj, val) {
                return accounting.formatMoney(val);
            }
        }],
            "bDeferRender": true,
        "bRetrieve": true,
        "bInfo": true,
        "bAutoWidth": true,
        "bDestroy": true,
            "sDom": 'T&;"clear"&;frtip',
            "oTableTools": {
            "aButtons": ["xls"],
                "sSwfPath": "../../Style Library/js/datatables/TableTools/media/swf/copy_csv_xls_pdf.swf",
        },
            "sSearch": "Filter",
            "fnDrawCallback": function () {
            //Add totals row
            var Columns = $("#example > tbody").find("> tr:first > td").length;
            $('#example tr:last').after('<tr><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td><td  class="total"></td></tr>');
            //Formating the Total row number to no decimals
            $("#example tr:last td:not(:first,:last)").text(function (i) {
                var t = 0;
                $(this).parent().prevAll().find("td:nth-child(" + (i + 2) + ")").each(function () {
                    t += parseFloat($(this).text().replace(/[\$,]/g, '') * 1);
                });
                return parseInt(t * 100, 10) / 100;
            });
            //Format the monthly expenditure and savings to currency formatFormating the currency
            var cell = new Array();
            cell[0] = $('#example tr:last td:nth-child(12)').text();
            cell[1] = $('#example tr:last td:nth-child(13)').text();
            $('#example tr:last').find('td:nth-child(12)').html(accounting.formatMoney(cell[0]));
            $('#example tr:last').find('td:nth-child(13)').html(accounting.formatMoney(cell[1]));
            $('#example tr:last').find('td:last').hide();
        } //hides extra td that was showing
    }); //End of Datatable()
}); //End of call.done function
$('#theTableDiv').slideDown();
} //end of run() function

我不是程序员,我我只是想学习。我将不胜感激任何帮助。在此先感谢

I'm not a programmer, I'm just trying to learn. I would appreciate any help. Thanks in advance

推荐答案

我猜你正在替换按钮所在页面的一部分。 (你真的需要为SO更整齐地格式化代码...使用JSFiddle.net及其TidyUp按钮。)

I would guess that you are replacing the part of the page where the button lives. (you really need to format your code more neatly for SO... use JSFiddle.net and their TidyUp button).

如果是这种情况你需要使用委托事件处理程序

If that is the case you need to use a delegated event handler:

$(document).on('click', '.myButton', function () {
    run()
});

这会侦听所需节点的静态祖先,然后运行当事件发生时,选择器然后它将该函数应用于导致事件的任何匹配元素。

This listens at a static ancestor of the desired node, then runs the selector when the event occurs, then it applies the function to any matching elements that caused the event.

document <如果您没有方便的祖先,/ code>是后备父级。不要将'body'用于委托事件,因为它有奇怪的行为。

document is the fallback parent if you don't have a convenient ancestor. Do not use 'body' for delegated events as it has odd behaviour.

这篇关于在jQuery中发出Ajax请求时,事件只会触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆