【问题标题】:how to call web service in ajax properly?如何正确调用 ajax 中的 Web 服务?
【发布时间】:2013-05-14 04:51:37
【问题描述】:

好的,这就是我想要做的,我想从活动目录中获取所有用户并将其放入列表中,所以我会从 ajax 调用 Web 服务,以获取所有用户并将其放入列表字符串,稍后我想在文本框中使用 jquery 自动完成功能,基于我之前获得的用户列表。

这就是我所做的:

  $(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 Internal Server Error - http://localhost:60525/SvcADUser.asmx/GetADUserList",如果我将 url 更改为 SvcADUser.asmx,它不会给出错误,但不会给我任何结果。

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

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

    }

【问题讨论】:

  • 在调试中运行asmx文件并手动输入关键字时,屏幕输出/错误是什么?
  • 不,我的 asmx 文件没有返回错误,它运行良好,它返回给我用户列表。
  • 好的,网络服务正在运行。尝试在您的 ajax 中添加成功和错误。看看您是否可以捕获 response.d 并从中检索数据。我自己挣扎了一段时间才把它弄好,所以我最终写了一个blog post关于它,这样我就不会忘记了。也许你会发现它有些用处。

标签: c# jquery asp.net web-services


【解决方案1】:

试试这个

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

【讨论】:

  • 由于某种原因您的代码工作正常,是因为 .ajax 之前的 JQuery 语句吗?
  • 我认为关键点是:(1.)确保 url 正确。 (2.)方法GetADUserList(string keyword)有参数'keyword',所以你必须为它发布数据,像这样--> data:'{keyword:"test"}'
猜你喜欢
  • 2019-01-02
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
  • 2015-11-18
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多