Ajax函数被多次触发并返回错误

时间:2019-05-13 17:14:51

标签: javascript jquery ajax wcf asp.net-ajax

我正在尝试使用对WCF的ajax调用将数据库中的信息加载到asp.net中的表中,该调用从实体表获取数据并将其加载到网页中。 我仅使用ajax调用一次,但是WCF被多次加载,并且始终返回正确的值,但是Ajax中的完整功能将转到错误功能 Ajax调用可以与其他WCF功能一起正常工作

WCF:

   #region Employees

    #region Get_Persons
    [OperationContract]
    [
    WebInvoke
    (
    Method = "POST",
    BodyStyle = WebMessageBodyStyle.WrappedRequest,
    ResponseFormat = WebMessageFormat.Json,
    RequestFormat = WebMessageFormat.Json
    )
    ]
    public Result_Get_Employees Get_Employees()
    {
        System.Diagnostics.Debug.WriteLine("wcf called"); //being printed multiple times
        #region Declaration And Initialization Section.
        string i_Ticket = string.Empty;
        Result_Get_Employees oResult_Get_Persons = new Result_Get_Employees();
        #endregion
        #region Body Section.
        FuelAppEntities entities = new FuelAppEntities();
            oResult_Get_Persons.My_Result = entities.tbl_User.ToList();
            #endregion
            #region Return Section
            System.Diagnostics.Debug.WriteLine("Result is: "+oResult_Get_Persons.My_Result.Count);//Returing the right value
            return oResult_Get_Persons;
        #endregion
    }
    #region Result_Get_Categories_List
    public partial class Result_Get_Employees : Action_Result
    {
        #region Properties.
        public List<tbl_User> My_Result { get; set; }
        #endregion
    }
    #endregion
    #endregion
    #endregion

    #region Action_Result
    public partial class Action_Result
    {
        #region Properties.
        public string ExceptionMsg { get; set; }
        #endregion
        #region Constructor
        public Action_Result()
        {
            #region Declaration And Initialization Section.
            #endregion
            #region Body Section.
            this.ExceptionMsg = string.Empty;
            #endregion
        }
        #endregion
    }
        #endregion

Javascript:

/* Members */
/* --------------------------------------------------------------- */
var _StartRow = 0;
var _Current_Page = 1;
var _Pages_Count = 0;
var _ChildWindow = "";
var js_Selected_News = null;
var _Person_Grid_Data = "";
var _Person_List = [];
var Params_Get_Person_By_Criteria_InList = new Object();
Params_Get_Person_By_Criteria_InList.data = ko.mapping.fromJS([]);

var _Params_Get_Person_By_Criteria_InList = ko.mapping.fromJS(Params_Get_Person_By_Criteria_InList);


$(document).ready
(
function () {
    console.log("ready");
    $("title", $(window.parent.document)).html('Persons');
    SetControlsProperties();
    setActiveNavigation(2, '');
}
);
/* --------------------------------------------------------------- */

/* SetControlsProperties */
/* --------------------------------------------------------------- */
function SetControlsProperties() {
    try {
        console.log("set control properties");
        /* ----------------- */
        ko.applyBindings(_Params_Get_Person_By_Criteria_InList, $("#news_page")[0]);
        /* ----------------- */
        Btn_Search_Click();
    }
    catch (e) {
        console.log("SetControlsProperties: " + e.message);
    }
}
/* --------------------------------------------------------------- */

/* Btn_Search_Click. */
/* --------------------------------------------------------------- */
function Btn_Search_Click() {
    try {
        console.log("btn search clicked");
        GetData();
    }
    catch (e) {
        console.log("Btn_Search_Click: " + e.message);
    }
}
/* --------------------------------------------------------------- */

/* GetData */
/* --------------------------------------------------------------- */
function GetData() {
    try {

        console.log("get data");
        _Params = ko.mapping.toJSON(_Params_Get_Person_By_Criteria_InList);
       // _Params = null;
        console.log("params: " + _Params);
        _Service_Method = "Get_Employees";
        var request = $.ajax({
        type: "POST",
        url: WCF.svc/Get_Employees,
        data: _Params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function (msg) {
            console.log(msg.login);
            Get_Employees_Completed(msg);
        },
        error: function (msg) {
            console.log("fail: " + msg.responseText + msg.statusText + msg.status)
        }
    });

        /* ---------------- */
    }
    catch (e) {
        console.log("GetData: " + e.message);
    }
}
/* --------------------------------------------------------------- */
// Get_Person_By_Criteria_Adv
/* --------------------------------------------------------------- */
function Get_Employees_Completed(i_Input) {
    try {
        console.log(i_Input.message);
        Handle_Employees_Grid(i_Input);
    }
    catch (e) {
        console.log("Get_Employees_By_Criteria_Adv_Completed: " + e.message);
    }
}
/* --------------------------------------------------------------- */

//Handle_Person_Grid
/* --------------------------------------------------------------- */
function Handle_Employees_Grid(i_Input) {
    try {
        var i_Person_List = [];
        console.log("Length: " + i_Input.My_Result.length)
        for (var i = 0; i < i_Input.My_Result.length; i++) {
            console.log(i_Input.My_Result[i])
            i_Person_List.push("Persons: "+i_Input.My_Result[i]);
        }
        var oTable = $('#tbl_data').dataTable();
        oTable.fnDestroy();
         $('#tbl_data tbody').html("");
        _Person_List = i_Person_List;
        _Params_Get_Person_By_Criteria_InList.data([]);
        _Params_Get_Person_By_Criteria_InList.data(i_Person_List);
        Module.init();

    }
    catch (e) {
        console.log('Handle_Person_Grid :' + e.message);
    }
}
/* --------------------------------------------------------------- */

1 个答案:

答案 0 :(得分:0)

public Result_Get_Employees Get_Employees()
{
    System.Diagnostics.Debug.WriteLine("wcf called"); //being printed multiple times
    #region Declaration And Initialization Section.
    string i_Ticket = string.Empty;
    Result_Get_Employees oResult_Get_Persons = new Result_Get_Employees();
    #endregion
    #region Body Section.
    FuelAppEntities entities = new FuelAppEntities();
        return entities.tbl_User.ToList();
        #endregion
        #region Return Section
        System.Diagnostics.Debug.WriteLine("Result is: "+oResult_Get_Persons.My_Result.Count);//Returing the right value
        return oResult_Get_Persons;
    #endregion
}

代码段中可能存在某些问题。一般来说,我们应该返回列表。以默认的WCF模板为例。
IService1.cs

[OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        List<CompositeType> GetDataUsingDataContract();
[DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
}

Service1.cs

  public List<CompositeType> GetDataUsingDataContract()
    {
        List<CompositeType> lists = new List<CompositeType>()
        {
            new CompositeType()
            {
                StringValue="Hello",
                BoolValue=true
            },
            new CompositeType()
            {
               StringValue="busy",
               BoolValue=false
            },
           new CompositeType()
           {
               StringValue="World",
               BoolValue=true
           }
        };
        return lists;
    }

Knockoutjs绑定。

  <script>
        var model = {
            composites: ko.observableArray()
        };

        function sendAjaxRequest(httpMethod, callback, url) {
            $.ajax("http://10.157.18.36:12000/service1.svc/getdatausingdatacontract", {
                type: httpMethod, success: callback
            });
        }

        function getAllItems() {
            sendAjaxRequest("GET", function (data) {
                model.composites.removeAll();
                for (var i = 0; i < data.length; i++) {
                    model.composites.push(data[i]);
                }
            });
        }

        $(document).ready(function () {
            getAllItems();
            ko.applyBindings(model);
        });
    </script>

HTML。

<div class="panel-heading">List Composites</div>
    <div class="panel-body ">

        <table class="table table-striped table-condensed">
            <thead>
                <tr>
                    <th>
                        StringValue
                    </th>
                    <th>
                        BoolValue
                    </th>
                </tr>
            </thead>
            <tbody data-bind="foreach:model.composites">
                <tr>
                    <td data-bind="text:StringValue"></td>
                    <td data-bind="text:BoolValue"></td>

                </tr>
            </tbody>
        </table>
    </div>

结果。 enter image description here 随时让我知道是否有什么可以帮助您的。