简体   繁体   English

无法从ajax获取数组

[英]Cant get array from ajax

I have asp.net application where need to implement autocomplete, I try to load list of names from server side and then deserealize it in js code, but have an 500 error, can anybody help me? 我有需要实现自动完成功能的asp.net应用程序,我尝试从服务器端加载名称列表,然后在js代码中将其反现实化,但是出现500错误,有人可以帮助我吗?

Unknown web method GetListofCompanies.
Parameter name: methodName

Code: 码:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetListofCompanies(string name) {
        var companies = _companyRepo.GetAll().Select(x => x.Name).ToList();

        // Create a JSON object to create the response in the format needed.
        JavaScriptSerializer oJss = new JavaScriptSerializer();

        // Create the JSON response.
        String strResponse = oJss.Serialize(companies);

        return strResponse;

    }

JS: JS:

var name = "";
        $.ajax({
            url: "Company.aspx/GetListofCompanies",
            type: "post",
            data: { name: name },
            dataType: "json",
            contentType: 'application/json',
            success: function (data) {
                // Get the data.
                var responseArray = JSON.parse(data.d);
                $("#txtName").autocomplete({
                    source: responseArray
                });
            }
        });
// Namespaces.
using System.Web.Services;
using System.Web.Script.Serialization;   

[WebMethod]
public static string GetListofCompanies(string name)
{
    List<string> companies = new List<string>();
    companies.Add("Company1");
    companies.Add("Company2");
    companies.Add("Company3");
    companies.Add("Company4");
    companies.Add("Company5");

    // Create a JSON object to create the response in the format needed.
    JavaScriptSerializer oJss = new JavaScriptSerializer();

    // Create the JSON response.
    String strResponse = oJss.Serialize(companies);

    return strResponse;
}

   // JS
   function request() {
        var name = "";
        var data = { name: name };
        $.ajax({
            url: "Default.aspx/GetListofCompanies",
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(data)
        }).success(function (data) {
            // do your stuff here
        })
        .fail(function (e) {
            alert("Error");
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM