我如何解决" Undefined"我的Jquery Ajax Web服务调用问题

时间:2014-10-30 12:50:31

标签: c# jquery asp.net ajax web-services

这是我的JS代码

function testService(test) {
var data = "{param2:\"" + test + "\"}";
$.ajax({
    type: "POST",
    url: "WebService1.asmx/HelloWorld",
    dataType: "json",
    data: data,
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        alert(response.d);
    },
    error: function(response) {
        alert(response.d);
    }
});
}

和我的网络方法。

/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[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 WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld(string val)
    {
        Service1 service1 = new Service1();
        Person person = service1.HelloWorld(val);
        return person.name;
    }
}

如果我试图在没有参数的情况下调用Web服务方法,这似乎工作正常,但是一旦我尝试将数据作为参数传递给数据值,我得到&#34; Undefined&#34;

2 个答案:

答案 0 :(得分:0)

c#中的

param名称必须与json对象键匹配

public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld(string param2)
    {
        Service1 service1 = new Service1();
        Person person = service1.HelloWorld(val);
        return person.name;
    }
}

答案 1 :(得分:0)

请查看javascript数据,并且helloworld方法parmeter都需要相同(单词)。

public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld(string param2)
    {
        Service1 service1 = new Service1();
        Person person = service1.HelloWorld(param2);
        return person.name;
    }
}