【问题标题】:Ajax function being fired multiple times and returning errorAjax 函数被多次触发并返回错误
【发布时间】:2019-05-13 17:14:51
【问题描述】:

我正在尝试使用 ajax 调用 WCF 将数据库中的信息加载到 asp.net 中的表中,WCF 从实体表中获取数据并将它们加载到网页中。 我只使用了一次 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);
    }
}
/* --------------------------------------------------------------- */

【问题讨论】:

  • 只是把它扔在那里,但successerror已被弃用,而是使用donefail
  • 您正在调用页面的 Btn_Search_Click() onload。您是否在实际单击按钮时再次调用它?按钮在哪里?是什么类型的?
  • @NawedKhan 只是命名错误,我复制了一些代码并对其进行了编辑以完成我想要的工作,但尚未编辑函数名称。 Btn_Search_Click() 只被调用一次。
  • 设置断点后,我意识到代码停留在 WCF 中,每次返回时,它都会再次执行整个函数,即使没有循环或任何其他调用

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


【解决方案1】:
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
}

代码 sn-ps 中可能有问题。一般来说,我们应该返回列表。以默认的 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>

结果。 如果有什么可以帮助的,请随时告诉我。

【讨论】:

  • 很抱歉代码中的错误,我现在编辑并修复了它。即使在尝试仅返回列表之后,它仍然会进入这个无限循环并在每次到达时调用整个 WCF 类 return oResult_Get_Persons
  • 修改返回类型为List而不是单个对象并添加数据契约属性,如参考代码sn-ps。最后,你可以使用 Postman 工具获取 Jason 对象吗?
  • 即使在添加数据契约和数据成员或将返回类型更改为列表之后它仍然会进入一个永无止境的调用 WCF 类的循环
  • 请求的 URL 是否正确? WCF.svc/Get_Employees。您是否能够通过使用其他工具(例如 PostMan)获得正确的 JSON 响应?此外,如何将数据绑定到 HTML 控件?我建议你可以做一个简单的测试,就像上面的例子。
猜你喜欢
  • 1970-01-01
  • 2016-04-04
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多