简体   繁体   中英

ASP.NET execute WebMethod with Jquery/AJAX

I have one WebMethod that will execute some DB search and return it's data in some HTML template. I need to execute this method using jquery to populate an area of the website but the problem is that my website URL/URI is dynamic.

My URL is http://site/school-name/home . The school-name will always change to indicate wich school i'm accessing.

I have accomplished so far:

$.ajax({
    type: "POST",
    url: "/Default.aspx/BuscaEquipe",
    data: { 'pIndex': pIndex, 'pLimite': 4, 'pUnidadeCE': codigoEmitente },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) {
        alert(response.d);
    },
    failure: function(response) {
        alert(response.d);
    }
});

and the WebMethod:

public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
    var objEquipe = new Equipe { EquipeUnidadeCE = pUnidadeCE, EquipeAtivo = 1 };
    var CaminhoImagem = Configuracoes.CaminhoVirtual + "Controles/Redimensiona.ashx?img=" + Configuracoes.CaminhoVirtual + "images/equipe/" + pUnidadeCE + "/";

    if (!objEquipe.Listar(objEquipe)) return "";

    var depoimentos = objEquipe.lstEquipe.Skip(pIndex).Take(pLimite);

    var objJson = new JavaScriptSerializer().Serialize(depoimentos.Aggregate("", (current, equipe) =>
            current + ("<div class='col-lg-3 col-md-3 col-sm-3'><img src='" + CaminhoImagem + equipe.EquipeImagem + "&w=400&h=400' alt='" + equipe.EquipeNome + "' class='img-circle img_perfil'><div class='nome_perfil text-center'>" + equipe.EquipeNome + "</div></div>")));

    return objJson;
}

Using like this i get a 401 Not Authorized and if i try to use my full URL http://site/school-name/Default.aspx/BuscaEquipe i get a 404.

PS I have already used this same method in another project and it worked fine but i can't figure out what's wrong in this one, i think it might be related to the URl but i'm not sure.

the problem is with your URL

Use the ResolveClientUrl() method

<%= ResolveUrl("~/Default.aspx/BuscaEquipe") %>

And you must Have [WebMethod] attribute before your static server function

[WebMethod]
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
   //Code
}

Your data:

var requestData= JSON.stringify({ pIndex: pIndex, pLimite: 4, pUnidadeCE: codigoEmitente })

and then

data:requestData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM