使用ajax和jquery通过webservice发回字符串数据

时间:2011-08-31 16:40:07

标签: c# .net web-services jquery

所有

我正在尝试将html数据传递给.NET / c#中存在的Web服务。我正在使用JQUERY,但继续收到“发布数据失败”的错误。我的ajax脚本或后面的代码中的语法错误了吗?谢谢你的帮助。

$(function () {

    $("[id$=rdbSaveAjax]").click(function () {  

    var markedUPHTML = $("[id$=wrapper]").html();
    var postData = "{'HTMLData' : '" + markedUPHTML + "'}";

    $.ajax({
            type: "POST",
            url: "Role.asmx/test",
            data: JSON.stringify({html: postData}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                alert("successfully posted data");
            },
            error: function (data) {
                alert("failed posted data");
                alert(JSON.stringify(postData));
            }

        }); 
    });

});

后面的webservice代码:

    /// <summary>
    /// Summary description for Role
    /// </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 Role : System.Web.Services.WebService
    {
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public string test(string html)
    {

        string strHTMLData = html;
        return html;

    }

}

3 个答案:

答案 0 :(得分:1)

var postData = "{'HTMLData' : '" + markedUPHTML + "'}";

如果markedUPHTML中包含单引号或双引号,则不会构建正确的字符串。在连接之前使用JavaScript escape方法。试试这个

var postData = "{'HTMLData' : '" + escape(markedUPHTML) + "'}";

然后在传递数据时,您不必使用strigify因为它已经是string。试试这个

 data: { html: postData }

答案 1 :(得分:0)

尝试在服务器端使用公共静态字符串,而不是公共字符串

答案 2 :(得分:0)

所有

我最终通过使用firebug找到了问题。每当我尝试回发连接到我的Role.asmx文件中的测试方法时,我都会收到500错误。我的解决方案是Cassini项目,因此我无法在配置本地IIS站点以更改权限方面做得很多。

相反,我在后面的代码中创建了一个方法,并将[WebMethod]放在方法名称的正上方。在我的代码背后,我没有设置在向解决方案添加web服务文件后通常会看到的任何声明。

[的WebMethod]    public static bool test(string strHTMLMarkup)    {         ....码    }

我希望这可以帮助其他人。

感谢。

相关问题