Javascript 如何使用带有 jquery 的 Ajax 调用 webservice?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10280368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:39:36  来源:igfitidea点击:

how to call webservice using Ajax with jquery?

javascriptajaxweb-servicesjquery

提问by user

I'm using the following code to call the webservice by using jQuery ajax. But It doesn't work? The webservice return the value in JSON format. How can I access the webservice through this code?

我正在使用以下代码通过使用 jQuery ajax 调用 web 服务。但它不起作用?Web 服务以 JSON 格式返回值。如何通过此代码访问网络服务?

<html>
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
    <script>
    $(document).ready(function () {
        $('input[id^="button"]').click(function () {
            alert('You have clicked ' + $(this).val());
            $.ajax({
                type: 'Get',
                url: 'http://localhost:56789/xxx/Handler.ashx?key=yyy ',
                success: function (data) {
                    alert(data);
                }
            });

        })
    })
    </script>

     <body>
        <div id="Sample_Div">
            <input type="button" id="button1" value="button1" />
        </div>
    </body>
</html>

回答by Clyde

Maybe you can try this one.

也许你可以试试这个。

 $.ajax({
        url: "../Services/Person.asmx/SavePersonById",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        type: "POST",
        data: '{ID:"00123"}',
        success: function (response) {
            //do whatever your thingy..
    }
});

Web Service Stuff:

网络服务内容:

[WebMethod]
public string SavePersonById(string ID)
    {
    //do some code here..
    dbContext.Save(ID,"Firstname","Lastnmae");
    return "Successfully Saved!";
    }

回答by shoaib soudagar

You can try this:

你可以试试这个:

$(document).ready(function () {
    $('#button').click(function () {
        $.ajax({
            type: "POST",
            url: "appWebservices/select.asmx/checkLogin",
            data: "{ ID:'" + $(this).val()+ "'}",
            contentType: "application/json;charset=utf-8",
            datatype: "json"
         });
     });
});

Write Web services as follow:

编写 Web 服务如下:

[WebMethod]
public string checkLogin(string ID)
{
    //Write your code here..
    //return value
}

know moredetails

了解更多详情