Call ASP.NET web service method from JavaScript

前端 未结 5 714
Happy的楠姐
Happy的楠姐 2020-12-20 04:45

I have the web service:

[WebMethod]
public void SendMail(string _name, string _email, string _message)
{
    //Create Mail Message Object with content that y         


        
相关标签:
5条回答
  • 2020-12-20 05:23

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

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

    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.

    0 讨论(0)
  • 2020-12-20 05:31

    You need to do something very important: Add the ScriptService attribute the class so that it can be called from a Javascript as in this example:

    [ScriptService]
    public class SimpleWebService : System.Web.Services.WebService 
    {
        // ...
    }
    

    http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptserviceattribute.aspx

    0 讨论(0)
  • 2020-12-20 05:33

    If it's an aspx page, you can add a ScriptManager with EnablePageMethods="true"attribute, and then call PageMethods.sendMail(name, email, message, onSuccess, onFail);

    0 讨论(0)
  • 2020-12-20 05:34

    Maybe you want to take a look at jQuery's ajax capabilities.

    0 讨论(0)
  • 2020-12-20 05:42

    You have to pass the three parameters from the cs code page, by calling like this way,

    service.SendMail(name, email, message);
    
    0 讨论(0)
提交回复
热议问题