Ajax call does not return proper result as string

2020-05-06 09:46发布

问题:

My ajax call. I am not getting the desired response as string. Can anyone help me in this regard. Thanks in advance.

function Function1() {
    alert("In Ajax Call");
    $.ajax({
        type: "POST",
        url: "abc.aspx/MyFunction1",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            $('#regularticker').html(res.d);
            //$('#futureticker').html(res.d);
            var d = new Date(); // for now
            $('#updateTime').html("Update at " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
            //alert(res.d.toString());
            alert(res);
            alert(res.d);
        },
        error: function (res) {
        }

    });
}

My Backend Function Called

[WebMethod]
public static string MyFunction1()
{
    try
    {
        if (true)
        {
            return "test"; 
        }
    }
    catch(Exception ex)
    {
        return ex.Message;
    }
}

回答1:

Your code is working fine in my machine.May be you forgot to call it by document load in Jquery. My code

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            Function1();
        });
        function Function1() {
            alert("In Ajax Call");
            var params = {};
            params.parameter = "passing string data";
            $.ajax({
                type: "POST",
                url: "abc.aspx/MyFunction1",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(params),//No data comment this section
                success: function (res) {
//                    $('#regularticker').html(res.d);
//                    //$('#futureticker').html(res.d);
//                    var d = new Date(); // for now
//                    $('#updateTime').html("Update at " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
//                    //alert(res.d.toString());
//                    alert(res);
                    alert(res.d);
                },
                error: function (res) {
                }

            });
        }
    </script>  

and my code behind file

        [WebMethod]
        public static string MyFunction1(string parameter)
        {
            //try
            //{
            //    if (true)
            //    {
            //        return "test";
            //    }
            //}
            //catch (Exception ex)
            //{
            //    return ex.Message;
            //}
            return parameter;
        }