简体   繁体   中英

Posting to WebMethod with ajax error

Step1:

I have defined my script as: on home.aspx page:

function ShowCurrentTime() {
    var post = ({
        method: "POST",
        url: "home.aspx/GetData",
        dataType: 'json',
        data: { name: "Mobile" },
        headers: { "Content-Type": "application/json" },
        success: function (data) {
            alert("here" + data.d.toString());
            alert(data.d);
        },
        failure: function() {
            alert("Fail");
        }
    });
}

Step2:

Call to the script function from button: it's on home.aspx page:

<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />

Step3:

Defined Web method at home.aspx.cs page:

[System.Web.Services.WebMethod]
public static string GetData(string name)
{
    return "Welcome";
}

I am getting:

JavaScript runtime error: Unable to get property 'd' of undefined or null reference

You have to stringify your data:

data: JSON.stringify({ name: "Mobile" })

And use ajax like this:

$.ajax({ ... });

Full script updated:

function ShowCurrentTime() {
    $.ajax({
        method: "POST",
        url: "home.aspx/GetData",
        dataType: 'json',
        data: JSON.stringify({ name: "Mobile" }),
        contentType: "application/json",
        success: function (data) {
            alert("here" + data.d.toString());
            alert(data.d);
        },
        failure: function() {
            alert("Fail");
        }
    });
}

Try this and tell me if it work :

<script type = "text/javascript">
                function ShowCurrentTime() {
                 var post = ({
                            method: "POST",
                            url: "home.aspx/GetData",
                            dataType: 'json',
                            data: { name: "Mobile" },
                            contentType: "application/json; charset=utf-8",
                      success: function (data) {
                          alert("here" + data.d.toString());
                              alert(data.d);},
                      failure: function() {
                          alert("Fail");}
                             });
                }
                </script>

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