我是jquery的新手ajax.i想要调用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;
}
当我打电话时这不起作用。执行错误部分。 请帮帮我。我做错了什么。
答案 0 :(得分:4)
您尚未发布确切的错误消息,但有几点需要注意:
请注意,您已在POST
来电中指定了$.ajax
,而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}"}
答案 1 :(得分:1)
尝试以下更改:
$(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;
}