使用jQuery Ajax调用Web方法

问题描述 投票:0回答:6

我想为搜索选项创建一个Autocomplete字段。我试过以下代码。

但是当Autocomplete函数执行时,web方法不会触发。会是什么原因?

这是jQuery函数:

<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>

这是web方法

    [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;
    }
asp.net json jquery autocomplete webmethod
6个回答
3
投票

确保通过在服务功能上使用断点来访问Web服务功能。请将您的脚本更改为:

<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>

1
投票

假设tags为您的文本框,请将数据设置为{ '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;
     },
 });

调试方法GetFarmersByName,

注意:检查是否在.asmx页面上取消注释[System.Web.Script.Services.ScriptService]


1
投票

在您的服务类之上添加[System.Web.Script.Services.ScriptService]

或者您可以在asp.net页面中执行此操作!

添加static关键字并将webservice更改为ASP.NET页面!

 public static string GetFarmersByName(string name)

例如:

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!");
                    }
                });

然后在A.aspx.cs中输入:

 [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);
        }

1
投票

再次发布!!!

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;
        }
    }
}

1
投票

将此方法粘贴到您调用此方法的代码隐藏文件中。将url更改为url:“Test.aspx / GetFarmersByName”然后测试它。它更干净的代码,而不是Web服务。

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;
}

0
投票

试试这个 -

<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);
                    }
                });
            }

        });
    });

和网络方法 -

[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;
}
© www.soinside.com 2019 - 2024. All rights reserved.