从JavaScript调用ASP.NET Web服务方法

GLe*_*aTi 1 javascript asp.net ajax web-services webmethod

我有网络服务:

[WebMethod]
public void SendMail(string _name, string _email, string _message)
{
    //Create Mail Message Object with content that you want to send with mail.
    MailMessage MyMailMessage = new MailMessage("gglebati@example.com", "gglebati@example.com", "This is the mail subject", "Just wanted to say Hello");

    MyMailMessage.IsBodyHtml = false;

    //Proper Authentication Details need to be passed when sending email from gmail
    NetworkCredential mailAuthentication = new NetworkCredential("myxxxxx@gmail.com", "xxxxxxxxx");

    //Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
    //For different server like yahoo this details changes and you can
    //get it from respective server.
   SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);

    //Enable SSL
    mailClient.EnableSsl = true;
    mailClient.UseDefaultCredentials = false;
    mailClient.Credentials = mailAuthentication;

    mailClient.Send(MyMailMessage);
}
Run Code Online (Sandbox Code Playgroud)

我有一个HTML页面.如何从我的html页面调用此函数?(此功能必须将消息发送到电子邮件)

Sae*_*ati 5

使用jQuery库.它使ajax调用成为一块蛋糕.然后按照这些项目:

  1. 在页面中添加一个HTML按钮,以便人们可以通过单击它来启动ajax进程
  2. 使用jQuery挂钩该按钮的click事件(或span,或div,或其他任何东西)
  3. 确保您ScriptService的Web服务具有属性(此属性意味着您可以从JavaScript调用您的服务)
  4. 将项目发送到您的Web服务方法

     $('#buttonId').click(function(){
         // Validating input
         $.ajax({
            type: 'POST',
            url: '/your-web-service-path.asmx/your-method-name',
            data: {} 
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function(r){},
            error: function(e){}
         });
    });
    
    Run Code Online (Sandbox Code Playgroud)

请注意,您必须从参数中生成JSON对象,并且JSON属性的名称应与Web服务参数的名称匹配.另请注意,作为r.d传递给ajax调用成功回调的对象,您可以使用Web服务的返回值.