4

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

Here is the Ajax call in 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 .aspx file:

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

And this is what I get in 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 returned value was whole html markup instead of "OK"?

4

3 回答 3

2

change datatype, try this

dataType: "json",
于 2013-08-14T11:40:44.967 回答
2

你可以看看以下

// 方法后面的代码声明为静态

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

你的按钮,点击它必须完成

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

为此的脚本

<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>
于 2013-08-14T12:04:22.867 回答
0

首先,我建议您查看以下文章并相应地更改您的代码:

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

这可能是原因,您可能缺少web.config条目。

于 2013-08-14T11:30:26.710 回答