从JavaScript中调用ASP.NET Web服务方法 [英] Call ASP.NET web service method from JavaScript

查看:138
本文介绍了从JavaScript中调用ASP.NET Web服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web服务:

[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);
}

和我有一个HTML页面。我怎么能说从我的html页面这样的功能? (此功能必须将消息发送到电子邮件)

and i have a html page. How can i call this function from my html page? (This function must send the message to email)

推荐答案

使用jQuery库。它使AJAX调用一块蛋糕。然后,按以下项目:

Use jQuery library. It makes ajax calls piece a cake. Then follow these items:

  1. 添加一个HTML按钮,您的网页,这样人们就可以通过单击开始AJAX程序
  2. 使用jQuery的挂钩到该按钮(或跨度,或者一个div,或其他任何东西)的Click事件
  3. 确保您已 ScriptService 在您的Web服务的属性(此属性意味着,你可以调用从JavaScript为您服务)
  4. 将内容发送至您的Web服务方法

  1. Add an HTML button to your page, so that people can start the ajax process by clicking it
  2. Use jQuery to hook into the click event of that button (or span, or a div, or anything else)
  3. Make sure you have ScriptService attribute on your web service (this attribute means that you can call your service from JavaScript)
  4. Send items to your web service method

 $('#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){}
     });
});

只是注意,你必须做出一个JSON对象,你的参数和JSON属性的名称应符合Web服务参数的名称。还要注意的是Web服务的返回值将提供给你作为 RD 对象传递给Ajax调用成功回调。

Just note that you have to make a JSON object out of your parameters and the name of the JSON properties should match the name of the web service parameters. Also note that the return value of the web service would be available to you as r.d object passed to success callback of ajax call.

这篇关于从JavaScript中调用ASP.NET Web服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆