我是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;

    }


这在我打电话时不起作用。它执行错误部分。
请帮助我。我做错了什么。

最佳答案

您尚未发布确切的错误消息,但是有几件事情要寻找:


请注意,您在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}"}

09-04 16:13
查看更多