简体   繁体   中英

How to call WebService client-side?

I am trying to access webservice from client-side using javascript. I have created webservice successfully. I have used it in Website project successfully, but it is Web Application project.

Here is my HTML code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript">
        function Test() {
            WebService1.HelloWorld(onS, onF);
        }
        function onS(r) { alert("Result"); }
        function onF(er) { alert("Error"); }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference InlineScript="true" Path="~/WebService1.asmx"/>
            </Services>
        </asp:ScriptManager>
        <input type="button" value="Call Service" onclick="Test()" />
    </div>
    </form>
</body>
</html>

Here is WebService code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace TestWebService
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

Now this code is not working.

I am using framework 3.5 and VS2012.

I find the answer. I should use namespace before web service name like this

function Test() {
    TestWebService.WebService1.HelloWorld(onS, onF);
}

This is the difference between Website project and Web Application project.

You can use the AJAX capability of JQuery to hit the web service. It is easy to use and very powerful.

Similar questions have been answered on stackoverflow.com before. Here is a link for you to check out.

jquery ajax get example

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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