获得jQuery ajax和asp.net webmethod xml响应工作

Tob*_*son 4 xml asp.net ajax jquery web-services

我有一个asp.net WebMethod,它返回一个XmlDocument对象.我可以使用jquery ajax成功调用该方法,但似乎无法使函数成功(服务器端webmethod使用正确的参数调用,但客户端方法失败并带有'undefined parser error').

重现,Asp.net C#:

[WebMethod]
public static XmlDocument test(string name)
{
    XmlDocument result = new XmlDocument();
    XmlElement root = result.CreateElement("Data");
    result.AppendChild(root);

    XmlElement element = result.CreateElement("AnElement");
    element.SetAttribute("Name", name);
    root.AppendChild(element);

    return result;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

function CallForData(name) {
    $.ajax({
        type: "POST",
        url: "AppName.aspx/test",
        data: "{'name': " + name+ "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function (response) { ParseXML(response); },
        error: function (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
    });
}
Run Code Online (Sandbox Code Playgroud)

如果dataType:"xml"被注释掉(自动),则调用success函数,但数据是方括号的加载,似乎表示空的json结构.我想要一个可以使用jQuery解析的XML响应.

我想我可能需要在XML文档中添加一些格式标识,但不确定.任何人都可以指出这个问题吗?

Tob*_*son 5

通过添加修复

[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]
Run Code Online (Sandbox Code Playgroud)

到网络方法.

感谢riteshtandon23在 这个帖子中