вызов веб-службы в кордове в Visual Studio 2015

Я разрабатываю приложение для Android с использованием инструментов apache Cordova в Visual Studio 2015. Я хочу вызвать веб-службу со своей индексной страницы в приложении 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";
    }

person Husain Tatiwala    schedule 29.02.2016    source источник


Ответы (2)


Ваши переменные параметры должны быть аналогичны параметрам 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";
    }
person deru    schedule 29.02.2016
comment
спасибо @deru за то, что нашли время ответить на мой вопрос. Однако проблема в моем коде заключалась в том, что мне нужно было включить CORS. Я добавил протоколы http и allow-access-origin = * в веб-конфигурацию моего сервера, и это помогло. - person Husain Tatiwala; 12.03.2016

Меня разбудил этот пример:

    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/

person danicode    schedule 03.06.2017