Ajax in jQuery with ASP.NET - return string

I am trying to write a simple ajax call with jQuery in ASP.NET.

Here is the Ajax call in the JavaScript file:

$.ajax( { url: "AjaxCall.aspx/GetSquare", dataType: "text", success: function (data) { alert(data); }, error: function () { alert("Ajax Error"); } }); 

And here is the web method in the .aspx file:

 [WebMethod] public string GetSquare() { return "OK"; } 

And here is what I get in the alert:

 !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title> </title></head> <body> <form method="post" action="GetSquare" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZLfZC2ZpNR/9g+3q7Z3ARCxIRMMXrN2MoePSYHvaiYH3" /> </div> <div> </div> </form> </body> </html> 

Why was the return value a solid html markup instead of OK?

+4
source share
3 answers

change data type try

 dataType: "json", 
+2
source

you can see the following

// Code behind the method declared static

 [WebMethod] public static string GetSquare() { return "OK"; } 

own button, the click of which must be executed

 <input type="button" id="button" value="Chnageurl" onclick="ajaxcall()" /> 

script for this

 <script type="text/jscript"> function ajaxcall(e) { $.ajax({ type: "POST", url: "Default.aspx/GetSquare", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert(data.d); }, error: function () { alert("Ajax Error"); } }); }; </script> 
+2
source

First of all, I suggest you familiarize yourself with the article below and change your code accordingly:

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

This may be the reason, maybe you are missing web.config .

0
source

Source: https://habr.com/ru/post/1497003/


All Articles