【问题标题】:posting string data back via webservice using ajax and jquery使用 ajax 和 jquery 通过 web 服务发回字符串数据
【发布时间】:2011-08-31 16:40:06
【问题描述】:

所有,

我正在尝试将 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;

    }

}

【问题讨论】:

    标签: c# .net web-services jquery


    【解决方案1】:

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

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

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

    然后在将数据传递给strigify 时,因为它已经是string。试试这个

     data: { html: postData }
    

    【讨论】:

    • 谢谢ShankarSangoli,但是,我倾向于得到同样的错误。不过,您的解决方案确实有意义。
    【解决方案2】:

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

    【讨论】:

    • 我在我的方法中添加了静态,但仍然没有运气。
    • 好的,具体的错误信息是什么?您是如何找到它的?使用浏览器控制台读取请求/响应。它要么失败,因为服务中的内部错误,找不到 Role.asmx 或其他东西。
    【解决方案3】:

    所有,

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

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

    [网络方法] 公共静态布尔测试(字符串 strHTMLMarkup) { ....代码 }

    我希望这对那里的其他人有所帮助。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多