在 Visual studio 2015 年在 cordova 中调用 Web 服务

calling a web service in cordova in Visual studio 2015

我正在 visual studio 2015 年使用 apache cordova 工具开发一个 android 应用程序。我想从 cordova 应用程序的索引页面调用网络服务,但我无法实现它.

这是HTML

 <div ><input type="button" id="callwebmethod" name="submit" /> <br /> </div>

这里是JS函数

 <script type="text/javascript">
    $('#callwebmethod').click(function () {
        var params = "{'msg':'From Client'}";
        $.ajax({
            type: "POST",
            url: "http://mysite/index.aspx/GetEmployees",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) { alert(result.d); }

        });


    })


</script>

这是网络方法

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

您的 var 参数必须与 WebMethod 的参数相似。将它们留空,然后再试一次。它们必须完全相同。

如果你想使用带有参数的网络方法,这里有一个工作示例:

    $.ajax({
        url: "http://systemservice/systemservice.asmx/App_Test",
        data: "{ par1: '" + xxx + "', par2: '" + xxx + "'}",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.d) {
                 //Do something
             }
        },
        error: function (xhr) {
            alert("An error occured: " + xhr.status + " " + xhr.statusText);
        }
    })


    [WebMethod]
    public string App_Test(string par1, string par2) {
        return "Hello";
    }

通过显示的错误函数,您还可以找出问题所在。

要在没有参数的情况下执行此操作,您只需将它们留空即可。

    data: "{}"


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

这个例子唤醒了我:

    var person = {};
 person.ID = $('#txtID').val();
 person.Name = "Amir";
 var pdata = { "p": person };
 $.ajax({
     type: "POST",
     contentType: "application/json; charset=utf-8",
     url: "/SampleService.asmx/GetPesonnelSalary",
     data: JSON.stringify(pdata),
     dataType: "json",
     async: true,
     success: function (data, textStatus) {

         if (textStatus == "success") {
             if (data.hasOwnProperty('d')) {
                 msg = data.d;
             } else {
                 msg = data;
             }
             alert(msg);

         }
     },
     error: function (data, status, error) {
         alert("error");
     }
 });

完整代码在这里:http://www.scriptiny.com/2012/12/calling-asmx-web-service-via-jquery-ajax-2/