简体   繁体   中英

ASP.NET ajax c# always returns undefined

I searched and tried for days now but I cant find any solution. I looked up nearly every tutorial and nearly every question on this board, but no code worked for me. (I know this is a duplicate question but since no other code worked at all, you are my last hope)

I'm trying to return a AJAX request from C# in ASP but no matter what it always returns undefinded even with code from tutorials.

Here is what I have in my Default.aspx

<script type="text/javascript">
    $(document).ready(function () {

     $.ajax({
         type: "POST",
         url: "Default.aspx/GetData",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (response) {
             alert(response.d);
         },
         failure: function (response) {
             alert(response.d);
         }
     });
 });
</script>

and here is my codebehind from Default.aspx.cs

[WebMethod]
public static string GetData()
{
    return "This string is from Code behind";
}

The Problem is: the c# method dont activate... I dont know why and I get no errormessage.

Can you pls help me? Thanks for your advice

I just copy pasted your code and it worked Like a charm as one can see in the following links

http://prntscr.com/baw6qb

I don't see what are you doing wrong, Please place a debugger in you JAVASCRIPT and see if its been called or Not. Rest is working fine in my Environment. There is no mismatch of text or no json instead of string needed. Please check you code thoroughly. you must be missing something some where
Output screenshot enter link description here

Update

在此处输入图像描述

Build format like this

{
    "employees":[
                  {"firstName":"John", "lastName":"Doe"},
                  {"firstName":"Anna", "lastName":"Smith"},
                  {"firstName":"Peter", "lastName":"Jones"}
    ]
}

and access through in jquery like employees[0].firstname

I had the exact same problem and it was driving me crazy. Finally, after hours of doing this and that, I checked the JSON response and it was like this : {"Message":"Authentication failed.", "StackTrace":null, "ExceptionType":"System.InvalidOperationException"}

And I searched for this issue and FINALLY found an answer over here ! Hope this helps you too! :)

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