如何使用Ajax和jquery调用webservice?

时间:2012-04-23 12:17:11

标签: javascript ajax web-services jquery

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

<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>

2 个答案:

答案 0 :(得分:2)

也许你可以试试这个。

 $.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..
    }
});

网络服务资料:

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

答案 1 :(得分:0)

你可以试试这个:

$(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"
         });
     });
});

编写Web服务如下:

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

know moredetails