$.ajax not calling WebService
本文关键字:WebService calling not ajax | 更新日期: 2023-09-27 18:11:58
我是jquery ajax的新手。我想调用web服务,但不工作。这是我的jquery代码。
$(document).ready(function () {
$('#TxBx_BasicSalary').focusout(function () {
var EmployeeId = $('#Hid_EmpID').val();
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: '/WebService/IncDedWebService.asmx/GetInceDed',
data: JSON.stringify({ id: EmployeeId }),
dataType: 'json',
success: function (data) {
alert("")
},
error: function () { alert("error"); }
});
});
这就是WebService方法。
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetInceDed(int id)
{
ClsSalary salary = new ClsSalary();
//var abc salary=.GetIncDedByEmpId(id);
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(salary.GetIncDedByEmpId(id));
return json;
}
当我调用时,这不起作用。它执行错误部分。请帮帮我。我做错了什么。
您还没有发布确切的错误消息,但有几件事需要查找:
-
请注意,您已在
$.ajax
调用中指定了POST
,而您的ScriptMethod
具有UseHttpGet = true
。我假设POST
。 -
包含Web/Script方法的类必须具有
[System.Web.Script.Services.ScriptService]
才能从ajax调用(根据asmx
代码模板添加的注释(
以下服务器代码适用于我:
[WebService(Namespace = "http://YourNameSpaceGoesHere/")]
[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 IncDedWebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string GetInceDed(int id)
{
ClsSalary salary = new ClsSalary();
//var abc salary=.GetIncDedByEmpId(id);
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(new ClsSalary
{
Amount = 1234,
Id = 123,
Name = "Basic Salary"
});
return json;
}
}
public class ClsSalary
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }
}
返回的json是:
{"d":"{'"Id'":123,'"Name'":'"Basic Salary'",'"Amount'":1234}"}
尝试这些更改:
$(document).ready(function () {
$('#TxBx_BasicSalary').focusout(function () {
var EmployeeId = $('#Hid_EmpID').val();
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: '/WebService/IncDedWebService.asmx/GetInceDed',
data: '{ "id": "' + EmployeeId + '" }', //THIS LINE
dataType: 'json',
success: function (data) {
var emp = $.toJson(data.d); //THIS
alert(emp.IncDeb.EmpID); //AND THIS
},
error: function () { alert("error"); }
});
});
这就是WebService方法。
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetInceDed(int id)
{
ClsSalary salary = new ClsSalary();
var abc salary=.GetIncDedByEmpId(id);
string json = "{'"IncDeb'":['"EmpId'":'"" + abc.EmpId +"'"]"; //And you have to keep going with the other members
return json;
}