Javascript 无法从ajax获取数组
我有一个asp.net应用程序需要实现自动完成,我尝试从服务器端加载名称列表,然后在js代码中反序列化,但有一个500错误,有人能帮我吗Javascript 无法从ajax获取数组,javascript,jquery,asp.net,ajax,Javascript,Jquery,Asp.net,Ajax,我有一个asp.net应用程序需要实现自动完成,我尝试从服务器端加载名称列表,然后在js代码中反序列化,但有一个500错误,有人能帮我吗 Unknown web method GetListofCompanies. Parameter name: methodName 代码: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetListofCompanies(stri
Unknown web method GetListofCompanies.
Parameter name: methodName
代码:
[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;
}
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
});
}
});
JS:
[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;
}
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
});
}
});
//名称空间。
使用System.Web.Services;
使用System.Web.Script.Serialization;
[网络方法]
公共静态字符串GetListofCompanies(字符串名称)
{
上市公司=新上市公司();
公司。添加(“公司1”);
公司。添加(“公司2”);
公司。添加(“公司3”);
公司。添加(“公司4”);
公司。添加(“公司5”);
//创建一个JSON对象以创建所需格式的响应。
JavaScriptSerializer oJss=新的JavaScriptSerializer();
//创建JSON响应。
字符串strResponse=oJss.Serialize(公司);
返回strResponse;
}
//JS
函数请求(){
var name=“”;
变量数据={name:name};
$.ajax({
url:“Default.aspx/GetListofCompanies”,
类型:“POST”,
contentType:'应用程序/json',
数据:JSON.stringify(数据)
}).成功(功能(数据){
//在这里做你的事
})
.失败(功能(e){
警报(“错误”);
});
}
能否显示ajax调用的响应?请确保url是正确的,是的,url是正确的,我在Company.aspx.csI中有此代码,假设您需要static关键字add static关键字并替换_companyrepoto Repository(),出现下一个错误:ExceptionType:“System.ArgumentException”消息:“无效的JSON基元:name。”