Chamando o serviço web com o jQuery Ajax em asp.net

Tenho um requisito que preciso de ligar para o serviço web usando o jQuery AJAX. Para isso eu criei WebService e criei um site de cliente. Infelizmente, não posso chamar-lhe isso. A chamada do AJAX não está a disparar.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
  public WebService()
  {   
    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
  }

  [WebMethod]
  public string getMessage(string name)
  {
    return "Hello " + name;
  }
}
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="GetMessage" Style="height: 26px"/>
<asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>.
$(document).ready(function () {
  $('#Button1').click(function () {
    alert(1);

    $.ajax({
      type: 'post',
      CORS: true,
      url: 'http://localhost/WebService/Hello.asmx?op=getMessage',
      contentType: "application/xml",
      data: { name: 'aa' },
      success: function (d) {
        alert(d);
      },
      failure: function (response) {
        debugger;
        alert(response.d);
      }
    });
  });
});
Estou a tentar aceder ao serviço web a partir da aplicação cliente.Estou a passar o ficheiro ASMX em URL path. Também dei referências de serviço. Infelizmente, não está a despoletar. Há algum erro no AJAX? Alguém pode ajudar? nisto? Não está a mostrar erros.

Author: Suhaib Janjua, 2017-04-26

2 answers

Editar:

Por uma questão de exaustividade e prova, criei um repositório de git desta solução e fiz o upload no GitHub . Você pode clonar ou baixar o código fonte, abri - lo no Visual Studio 2012 (ou+) e carregar em F5 para verificar se a solução está a funcionar. Você pode modificá-lo de acordo com sua necessidade.


Resposta Original:

Espero que estejas a usar a referência jQuery, porque não a mencionaste no livro. pergunta. Bem dado abaixo está a solução de trabalho do seu código WebService consumindo em ASP.NET usando jQuery.

Bem use o caminho relativo de modo que ele não vai fazer um problema para você se você executar o seu aplicativo em desenvolvimento ou de implantação. Em segundo lugar, neste momento, está apenas a seleccionar asp.net controla id como é que eu sei que vai causar-lhe um problema mais tarde quando você mover o código Os controles de páginas de crianças. Então use o selector jQuery algo como: $("[id*=Button1]") para seleccionar o elemento correctamente.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("[id*=Button1]").click(function () {
            var message = $("[id*=TextBox1]").val();

            $.ajax({
                type: "POST",
                url: "WebService.asmx/getMessage",
                data: "{ name: '" + message + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.responseText);
                },
                failure: function (r) {
                    alert(r.responseText);
                }
            });
            return false;
        });
    });
</script>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="GetMessage" Style="height: 26px"/>
<asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

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

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService
{

    public WebService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string getMessage(string name)
    {
        return "Hello " + name;
    }
}

Resultado:

enter image description here

Resposta:

enter image description here

 0
Author: Suhaib Janjua, 2017-04-26 11:32:04

É porque os botões ASP Button1 não estão disponíveis no javascript, por isso adiciona uma classe a esse botão como,

<asp:Button ID="Button1" class="getMessage" runat="server" Text="GetMessage" Style="height: 26px"/>

E em uso jQuery,

$(document).ready(function () {
  $('.getMessage').click(function () { // use getMessage class here
    alert(1);
    $.ajax({
      type: 'post',
      // CORS: true, remove this line there is no settings like CORS
      url: 'http://localhost/WebService/Hello.asmx?op=getMessage',
      contentType: "application/xml",
      data: { name: 'aa' },
      success: function (d) {
        alert(d);
      },
      failure: function (response) {
        debugger;
        alert(response.d);
      }
    });
  });
});
 0
Author: Rohan Kumar, 2017-04-26 09:01:02