【问题标题】:Ajax call does not return proper result as stringAjax 调用不会以字符串形式返回正确的结果
【发布时间】:2016-04-12 10:18:39
【问题描述】:

我的 ajax 调用。我没有得到所需的字符串响应。任何人都可以在这方面帮助我。提前致谢。

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) {
        }

    });
}

我的后端函数调用

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

【问题讨论】:

  • 你得到什么回应?
  • 您将 dataType 设置为“json”,但未返回 json 格式的内容。您应该在返回之前尝试将字符串编码为 json 格式。也许它可以解决您的问题。

标签: jquery asp.net ajax


【解决方案1】:

您的代码在我的机器上运行良好。可能是您忘记在 Jquery 中通过文档加载来调用它。我的代码

    <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>  

还有我的代码隐藏文件

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

【讨论】:

    猜你喜欢
    • 2012-06-23
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多