2011-09-01 32 views
1

方法我有Web服務:電話ASP.NET Web服務從JavaScript

[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("[email protected]", "[email protected]", "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("[email protected]", "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頁面調用這個函數? (此功能必須將郵件發送到電子郵件)

+0

[$ .ajax和webmethod/pagemethods]的可能重複(http://stackoverflow.com/questions/14 58969/ajax-and-webmethod-pagemethods) –

+0

你是否願意添加jQuery庫? –

+1

@Mr。失望 - 我不認爲這是該頁面的重複。 –

回答

5

使用jQuery庫。它使阿賈克斯呼籲一塊蛋糕。然後,按以下項目:

  1. 添加HTML按鈕,您的網頁,讓人們可以通過點擊它
  2. 使用jQuery啓動AJAX程序掛接到該按鈕的Click事件(或跨度,或DIV,或其他任何東西)
  3. 請確保您有您的網絡服務ScriptService屬性(此屬性意味着你可以從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){} 
        }); 
    }); 
    

請注意,您必須從參數中創建JSON對象,並且JSON屬性的名稱應該與Web服務參數的名稱匹配。另請注意,將Web服務的返回值作爲r.d對象傳遞給ajax調用的成功回調。

+0

如何發佈參數:(字符串_email,字符串_email,字符串_message)>? – GLeBaTi

+1

創建此對象:'{string_name:'value1',string_email:'value2',string_message:'value3'}'。 –

+1

@_glebati:see where data:{}?You可以放:data:{'_message':'hello world','_ name':'john smith','_ email':'[email protected]'}。重要的是您的參數名稱在Web服務匹配數據參數在JavaScript端的名稱和數據參數是有效的JSON格式。 – Icarus

0

如果它是一個aspx頁面,您可以添加一個帶有EnablePageMethods =「true」屬性的ScriptManager,然後調用PageMethods.sendMail(名稱,電子郵件,消息,onSuccess,onFail) ;

+0

它與javascript – GLeBaTi

0

也許你想看看jQuery的ajax功能。

+1

+1是simle html頁面,因爲這是一個有效的答案,但是您應該提供更多的細節。 –

+0

kind'a like saying「您可能想要閱讀.Net Web Services文檔@ https://msdn.microsoft.com/en-us/library/ms950421.aspx以獲取更多信息。 –

0

你要通過三個參數從CS代碼頁,通過這樣調用,

service.SendMail(name, email, message);