简体   繁体   English

通过.NET Web服务使用jQuery.ajax()提交HTML表

[英]Submit HTML table with jQuery.ajax() with a .NET web service

I'm pretty new to jQuery and JavaScript but I'm wanting to submit an email to a .NET web service I wrote. 我对jQuery和JavaScript相当陌生,但是我想向我编写的.NET Web服务提交电子邮件。 I've tested the web service with some simple values in my data but I was hoping I could submit a whole table that I populate server side after doing some client side and server side validation. 我已经用数据中的一些简单值测试了Web服务,但是我希望我可以提交经过客户端和服务器端验证后填充服务器端的整个表。

This works: 这有效:

data: '{ strFrom: "abcd@abc.edu", to: "abcd@abc.edu", cc: "abcd@abc.edu", subject: "test subject", body: "test body" }'

However, like I said I have this table I've populated with responses to the form and when I do a var body = $("#divSuccessDetails").html(); 但是,就像我说的那样,我已经在该表中填充了对表单的响应,并且当我执行var body = $(“#divSuccessDetails”)。html();时, and pass that in instead of "test body" I get an invalid object response. 并将其传递给而不是“测试正文”,我得到一个无效的对象响应。 I've tested the results of the table I'm selecting and it's along the lines of this: 我已经测试了我选择的表的结果,它遵循以下原则:

<table id="ctl00_ContentPlaceHolder1_tblSuccessDetails" class="successDetails" style="width:80%;">
    <tbody><tr>
        <td class="successHeading" colspan="2">
    Reporting Category
    </td>
    </tr>
    <tr>
        <td>
        <span id="ctl00_ContentPlaceHolder1_lblBilling">Billing Provider: <b></b></span>
    </td>
        <td rowspan="1">
        <span id="ctl00_ContentPlaceHolder1_lblCategory">Reporting Category: </span></td>
    </tr>
    <tr>

My web service method is this: 我的Web服务方法是这样的:

 public string Email(string strFrom, string to, string cc, string subject, string body) {
    try
    {
        MailMessage objMail = new MailMessage();
        MailAddress from = new MailAddress(strFrom);
        objMail.From = from;
        objMail.To.Add(to);
        objMail.CC.Add(cc);
        objMail.Subject = subject;
        objMail.Body = body;
        SmtpClient smtp = new SmtpClient("pobox.abc.edu");
        smtp.Send(objMail);

        return "{\"form\": { \"successful\": \"true\" }}";
    }
    catch (Exception ex)
    {
        return "{\"form\": { \"successful\": \"false\" }, {\"exception\": {\"ex\": \"" + ex.Message + "\" }}";
    }
}

The error message I'm receiving is along these lines: 我收到的错误消息大致如下:

"Invalid object passed in, ':' or '}' expected. (176): { strFrom: "abcd@abc.edu", to: "abcd@abc.edu", cc: "abcd@abc.edu", subject: "IDX Provider Form by IDX Provider Form by abcd", body: " <table id="ctl00_ContentPlaceHolder1_tblSuccessDetails" class="successDetails" style="width:80%;"> <tbody><tr> <td class="successHeading" colspan="2">

I was just hoping to pass it in as a string because that's what I'm receiving.. I've put plenty of HTML in strings that I've used for an emailobject before but this is the first time I've tried to pass it through AJAX. 我只是希望将其作为字符串传递,因为那是我收到的。.我已经在用于电子邮件对象的字符串中放入了大量HTML,但这是我第一次尝试传递通过AJAX。

If you try to pass an entire HTML table full of HTML elements to a web service your going to run into issues with HTML characters (eg Quotes, Double Quotes, etc...). 如果尝试将包含HTML元素的整个HTML表传递到Web服务,则会遇到HTML字符问题(例如,引号,双引号等)。 You can escape the characters, but I think your better off finding the specific data values you want to send in your HTML table and assigning them to a data object, since this will result in only sending "data" vs. "markup and data". 您可以转义字符,但是我认为最好在HTML表中找到要发送的特定数据值并将它们分配给数据对象,因为这样只会导致发送“数据”与“标记和数据” 。 If you passed an entire HTML table to the server, you would then have to parse the HTML document to pull out your values. 如果将整个HTML表传递给服务器,则必须解析HTML文档以提取值。

As an alternative solution, you could post the FORM to a page with jQuery where it could be processed. 作为替代解决方案,您可以将FORM发布到可以使用jQuery处理的页面。

$.post("FormProcessor.aspx", $("#testform").serialize());

[Update] [更新]

If you just want to send HTML markup of a table to the server, you'll need to HTML Encode the results, and pass the value as a string value to the server. 如果仅要将表的HTML标记发送到服务器,则需要对结果进行HTML编码,然后将值作为字符串值传递给服务器。

    jQuery.fn.EncHTML = function () {
        return String(this.html())
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    };

Here is how you would use this with a GridView. 这是您将其与GridView一起使用的方式。

var html = $('#<%= Sample.ClientID %>').EncHTML();

Here is how to do a standard jQuery AJAX request to a ASMX/WCF Service. 这是对ASMX / WCF服务执行标准jQuery AJAX请求的方法。

$.ajax({
    type: 'POST',
    url: '/TableManager.asmx/Process',
    data: JSON.stringify({ tableContents: html }),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
});

This calls the "Process" method of the TableManager.asmx service. 这将调用TableManager.asmx服务的“ Process”方法。 It expects a variable called "tableContetns" of type String to be passed. 它期望传递一个名为String的变量“ tableContetns”。 It has a return type of VOID so nothing is sent back to the client/page, but this could be changed to string so you could send a message back that the table/data was processed. 它具有VOID的返回类型,因此没有任何内容发送回客户端/页面,但是可以将其更改为字符串,以便您可以发送回一条消息,说明已处理了表/数据。

NOTE: I'm also using the JSON.Org stringify function to properly JSON encode my object being sent to the server. 注意:我还使用JSON.Org字符串化函数正确地对发送到服务器的对象进行JSON编码。

Here is the web method on the server. 这是服务器上的Web方法。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class TableManager : WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void Process(string tableContents)
    {
        var table = Server.HtmlDecode(tableContents);
        // Do Something (Email, Parse, etc...).
    }
}

The table pulled back from the client will not include the "table" tags, so you'll need to throw those in yourself. 从客户端拉回的表将不包含“ table”标签,因此您需要将它们自己扔掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM