C# 如何在ajax中正确调用web服务?

C# 如何在ajax中正确调用web服务?,c#,jquery,asp.net,web-services,C#,Jquery,Asp.net,Web Services,好的,这就是我要做的,我想从active directory中获取所有用户并将其放入列表,所以我会从ajax调用一个web服务,获取所有用户并将其放入列表字符串,然后我想在文本框中基于我之前获得的用户列表使用jquery autocomplete 我就是这么做的: $(document).ready(function () { // Load data then initialize plugin: $.ajax({

好的,这就是我要做的,我想从active directory中获取所有用户并将其放入列表,所以我会从ajax调用一个web服务,获取所有用户并将其放入列表字符串,然后我想在文本框中基于我之前获得的用户列表使用jquery autocomplete

我就是这么做的:

  $(document).ready(function () {

            // Load data then initialize plugin:
            $.ajax({
                url: '/SvcADUser.asmx/GetADUserList',
                dataType: 'json'
            }).done(function (source) {

                var countriesArray = $.map(source, function (value) { return { value: value }; }),
                    countries = $.map(source, function (value) { return value; });

                // Setup jQuery ajax mock:
                $.mockjax({
                    url: '*',
                    responseTime: 200,
                    response: function (settings) {
                        var query = settings.data.query,
                            queryLowerCase = query.toLowerCase(),
                            suggestions = $.grep(countries, function (country) {
                                return country.toLowerCase().indexOf(queryLowerCase) !== -1;
                            }),
                            response = {
                                query: query,
                                suggestions: suggestions
                            };

                        this.responseText = JSON.stringify(response);
                    }
                });



                // Initialize autocomplete with local lookup:
                $('#MainCT_dtvJobVac_PIC').autocomplete({
                    lookup: countriesArray,
                    onSelect: function (suggestion) {
                        $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
                    }
                });

            });

        }());

    }());
但这给我带来了一个错误,
“NetworkError:500内部服务器错误-http://localhost:60525/SvcADUser.asmx/GetADUserList“
,如果我将url更改为SvcADUser.asmx,它不会给出错误,但不会给出结果

我做错了什么?顺便说一句,这是我的web服务代码:

 [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 SvcADUser : System.Web.Services.WebService
    {
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        [WebMethod]
        public List<string> GetADUserList(string keyword)
        {
            List<string> alluser = new List<string>();

            using (var context = new PrincipalContext(ContextType.Domain, "weekendinc.com"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;

                        alluser.Add((string)de.Properties["samAccountName"].Value);
                    }
                }
            }

            var filtereduser = alluser.Where(usr => usr.ToLower().StartsWith(keyword.ToLower()));

            return filtereduser.ToList();
        }

    }
[WebService(命名空间=”http://tempuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//要允许使用ASP.NET AJAX从脚本调用此Web服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
公共类SvcADUser:System.Web.Services.WebService
{
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
[网络方法]
公共列表GetADUserList(字符串关键字)
{
List alluser=新列表();
使用(var context=newprincipalcontext(ContextType.Domain,“weekendinc.com”))
{
使用(var searcher=newprincipalsearcher(newuserprincipal(context)))
{
foreach(searcher.FindAll()中的var结果)
{
DirectoryEntry de=result.getUnderlineObject()作为DirectoryEntry;
添加((字符串)de.Properties[“samAccountName”].Value);
}
}
}
var filtereduser=alluser.Where(usr=>usr.ToLower().StartsWith(keyword.ToLower());
返回filtereduser.ToList();
}
}
试试这个

jQuery.ajax({
            type: 'POST',
            contentType: 'application/json;',
            data: '{keyword:"test"}',
            dataType: 'json',
            async: true,
            url: 'SvcADUser.asmx/GetADUserList',
            success: function (result) {
                alert(result.d);
            }
        });

在调试中运行asmx文件并手动输入关键字时,屏幕输出/错误是什么?不,我的asmx文件没有返回错误,它工作正常,它返回我的用户列表。确定web服务正在工作。尝试在ajax中添加成功和错误。看看是否可以捕获response.d并从中检索数据。我自己挣扎了一段时间才把它做好,所以我最后写了一篇关于它的文章,这样我就不会忘记了。也许您会发现它有一些用处。出于某种原因,您的代码能够正常工作,是因为JQuery语句在.ajax之前吗?我认为关键点是:(1)确保url是正确的。(2.)方法GetADUserList(string关键字)具有参数'keyword',因此您必须为其发布数据,如-->数据:'{keyword:“test”}'