Call a web method using jQuery Ajax

2019-06-11 20:24发布

问题:

I want to create an Autocomplete field for a search option. I have tried with following code.

But the web method doesn't fire when the Autocomplete function is execution. What will be the reason ?

Here is the jQuery function:

<script type="text/javascript">
    $(function () { $("#<%=tags.ClientID %>").autocomplete({
         source:function (request, response) {
         $.ajax ({
             type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "~/Services/AutoComplete.asmx/GetFarmersByName",
            data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
            dataType: "json",
            async: true,
            dataFilter: function (data) { return data; },
            success: function (data) {
                      response($(data.d, function (item) {
                                return            {
                                    value: item.AdrNm
                                }
                       }));
                     },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                }

            });
        });
 </script>

Here is the web method

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
    {
        this._personalData = new personalData();
        int cky = 45;
        CdMa cdMas = new CdMa();
        cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
        int prefixKy = cdMas.CdKy;

        List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();

        list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
        return list;
    }

回答1:

Make sure you hit the webservice function by having breakpoint on your service function. Please change your script to below:

<script type="text/javascript">
    $(function () {
        $("#<%=tags.ClientID %>").autocomplete
        ({

            source:
            function (request, response) {
                $.ajax
                ({
                    url: " <%=ResolveUrl("~/Services/AutoComplete.asmx/GetFarmersByName") %>",

                    data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",

                    dataType: "json",

                    type: "POST",

                    contentType: "application/json; charset=utf-8",                   

                    async: true,

                    dataFilter: function (data) { return data; },

                    success: function (data) 
                    {
                        response($(data.d, function (item) 
                        {
                            return
                            {
                                value: item.AdrNm
                            }
                        }));
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            }

        });
    });
</script>


回答2:

Assuming tags as your textbox, set data as { 'name': '" + request.term + "'}

$("#<%=tags.ClientID %>").autocomplete({
     source: function (request, response) {
         $.ajax({
             url: "Services/AutoComplete.asmx/GetFarmersByName",
             data: "{ 'name': '" + request.term + "'}",
             dataType: "json",
             type: "POST",
             contentType: "application/json; charset=utf-8",
             success: function (data) {
                 response($.map(data.d, function (item) {
                     return {
                         label: item.split('-')[0],
                         val: item.split('-')[1]
                     }
                 }))
             },
             error: function (response) {
                 alert(response.responseText);
             },
             failure: function (response) {
                 alert(response.responseText);
             },
         });
     },
     minLength: 0,
     focus: function () {
         // prevent value inserted on focus
         return false;
     },
 });

debug on method GetFarmersByName,

NOTE: Check have you uncomment [System.Web.Script.Services.ScriptService] on .asmx page.



回答3:

Above your service class add [System.Web.Script.Services.ScriptService]

Or you can do this in an asp.net page!

add the static keyword and change the webservice to ASP.NET page!

 public static string GetFarmersByName(string name)

For example:

A.aspx:

  $.ajax({
                    type: "POST",
                    url: "A.aspx/GetSN",
                    data: {},
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    async:false,
                    success: function (json) {
                        var msg = JSON.parse(json.d);
                        sn = msg;
                    },
                    failure: function () {
                        alert("Sorry,there is a error!");
                    }
                });

Then in your A.aspx.cs type in:

 [WebMethod]
        public static string GetSN()
        {
            Random RN = new Random();
            string year = DateTime.Now.ToString("yy").ToString();
            string MonAndDate = DateTime.Now.ToString("MMdd").ToString();
            string Hour = DateTime.Now.ToString("HHMMss").ToString() + DateTime.Now.Millisecond.ToString() + RN.Next(100, 900).ToString();
            string SerialNumber = year + MonAndDate + Hour;
            return JsonConvert.SerializeObject(SerialNumber);
        }


回答4:

Post again!!!

Test.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.9.0.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#Button1").bind("click",function(){
                $.ajax({
                    type: "POST",
                    url: "Test.asmx/GetFarmersByName",
                    data:"{'aaa':'zhangsan'}",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (json) {

                    },
                    failure: function () {
                        alert("Sorry,there is a error!");
                    }
                });
            })
        })

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" value="button" />
    </div>
    </form>
</body>
</html>

Test.asmx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

namespace TestWebForm
{
    /// <summary>
    /// Summary description for Test
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Test : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<string> GetFarmersByName(string aaa)
        {
            List<string> list = new List<string>();
            list.Add(aaa);
            return list;
        }
    }
}


回答5:

Paste this method inside code behind file where you are calling this method. Change url to url: "Test.aspx/GetFarmersByName" and then test it. Its much clean code rather then Web Service.

using System.Web.Script.Services;
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
    List<string> list = new List<string>();
    list.Add(aaa);
    return list;
}


回答6:

try this -

<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
     source:function (request, response) {
     var obj = JSON.Stringfy("{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}");
     $.ajax ({
         type: "POST",
        url: "~/Services/AutoComplete.asmx/GetFarmersByName",
        data: obj,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        dataFilter: function (data) { return data; },
        success: function (data) {
                  response($(data.d, function (item) {
                            return            {
                                value: item.AdrNm
                            }
                   }));
                 },
       error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            }

        });
    });

and the webmethod-

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
    this._personalData = new personalData();
    int cky = 45;
    CdMa cdMas = new CdMa();
    cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
    int prefixKy = cdMas.CdKy;

    List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();

    list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
    return list;
}