Je souhaite appeler un service Web à partir de javascript.
C'est mon code:
var method="GetStock"; var url = "http://www.mywebsite.ro/ServiceGetStock.asmx"; $.ajax({ type: "POST", url: url + "/GetStock", data: "{variant_id='1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccessCall, error: OnErrorCall }); function OnSuccessCall(response) { alert(response.d); } function OnErrorCall(response) { alert(response.status + " " + response.statusText); }
Mon code ServiceGetStock.asmx:
[WebMethod] public string GetStock(int variant_id) { try { ProductVariant variant = ProductVariantManager.GetProductVariantByID(variant_id); return variant.Stock.ToString(); } catch (Exception ex) { return ex.Message; } }
J'ai reçu le message d'erreur:
POST http://www.mywebsite.ro/ServiceGetStock.asmx/GetStock 500 (Erreur interne du serveur)
[METTRE À JOUR]
J'ai oublié de mentionner que j'ai ajouté dans webconfig de projet (avec webservice) parce que j'ai eu l'erreur:
XMLHttpRequest ne peut pas charger http://www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld . Aucun en-tête 'Access-Control-Allow-Origin' n'est présent sur la ressource demandée. Origine 'http: // localhost: 11300' n'est donc pas autorisé à accéder.
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> </customHeaders> </httpProtocol>
Ok les gars. J'ai trouvé le problème. Lorsqu'un fichier ASMX est créé, vous devez lire toutes les lignes de commentaires. Pour permettre à ce service Web d'être appelé à partir du script, à l'aide d'ASP.NET AJAX, décommentez la ligne suivante.
//[System.Web.Script.Services.ScriptService]
La fonction GetStock est donc:
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetStock(string variant_id) { SendEmail.SendErrorMail("in"+ variant_id); try { ProductVariant variant = ProductVariantManager.GetProductVariantByID(Convert.ToInt32(variant_id)); return variant.Stock.ToString(); } catch (Exception ex) { return ex.Message; } }
Et le code Ajax est:
var url = "http://www.mywebsite.ro/ServiceGetStock.asmx"; $.ajax({ type: "POST", url: url + "/GetStock", data: "{variant_id:'1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccessCall, error: OnErrorCall }); function OnSuccessCall(response) { alert(response.d); } function OnErrorCall(response) { alert(response.status + " " + response.statusText); }
Problème résolu! Merci à tous pour des conseils …….