开发者

Getting jQuery ajax and asp.net webmethod xml response to work

开发者 https://www.devze.com 2023-01-31 09:09 出处:网络
I have an asp.net WebMethod that returns an XmlDocument object. I can successfully call the method using jquery ajax, but can\'t seem to get the function to succeed (server side webmethod gets called

I have an asp.net WebMethod that returns an XmlDocument object. I can successfully call the method using jquery ajax, but can't seem to get the function to succeed (server side webmethod gets called with correct parameters but client side method fails with 'undefined parser error').

To reproduce, 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;
}

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: fun开发者_StackOverflow中文版ction (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
    });
}

If dataType: "xml" is commented out (automatic) the success function is called but the data is a load of square brackets that seem to indicate an empty json structure. I want an XML response that I can parse using jQuery.

I think I possibly need to add some format identification to the XML document but aren't sure. Can anyone point out the problem?


Fixed by adding

[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]

to the web method.

Credit to riteshtandon23 in this thread

0

精彩评论

暂无评论...
验证码 换一张
取 消