【问题标题】:Receiving json via ajax asp.net通过 ajax asp.net 接收 json
【发布时间】:2013-04-29 23:10:47
【问题描述】:

我在函数 ShowFavorits 中的变量数据是未定义的,即使我的 ajax 调用确实返回了一个 json 字符串。

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

    function AjaxGet() {
        var param = "{'_userID': '1337'}";
        $.ajax({
            type: "POST",
            url: "/webservices/MinSide.asmx/GetFavorits",
            data: param,
            contentType: "application/json;",
            dataType: "json",
            success: function (data) {
                if (data.hasOwnProperty("d")) {                      
                    return (data.d);
                }
            },
            error: function (data) {
                //error
            }
        });
    }

    function ShowFavorits() {
        var data = AjaxGet();

        $("#addedList").html(
        $("#addedTemplate").render(data)
        );
    }
});

        [WebMethod]
    public string GetFavorits(string _userID)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.MaxJsonLength = int.MaxValue;
        string JsonData = string.Empty;

        var db = new ModelDataContext();
        var list = db.table.Where(x => x.userID == _userID).OrderBy(x=> x.TimePin).ToList();

        JsonData = jss.Serialize(list);  
        return (JsonData);
    }

为什么我不能从我的 ajax 返回结果?

希望有人可以帮助我,现在调试这个已经卡了几个小时了。

提前致谢。

【问题讨论】:

标签: javascript asp.net ajax


【解决方案1】:

AjaxGet 中对$.ajax 的调用是异步的:函数返回 undefined,因为 ajax 调用尚未完成。

您应该将对 ShowFavourits 的调用移动到 ajax 成功函数中,以便在 ajax 调用完成/成功后执行

<script type="text/javascript">
$(document).ready(function () {
    // Kick-off the ajax request
    AjaxGet();

    function AjaxGet() {
        var param = {_userID: '1337'};
        $.ajax({
            type: "POST",
            url: "/webservices/MinSide.asmx/GetFavorits",
            data: param,
            dataType: "json",
            success: function (data) {
                if (data.hasOwnProperty("d")) {                      
                    ShowFavorits(data.d); // Pass the data to the template
                }
            }
        });
    }

    function ShowFavorits(data) {
        $("#addedList").html(
            $("#addedTemplate").render(data)
        );
    }
});

【讨论】:

  • 您好,感谢您的帮助。我现在将数据发送到 ShowFavorits() 但它不起作用。如果我将 AjaxGet 中的 JSON 硬编码为 ex var data2 并将其传递给渲染,那么它就可以工作了。
  • 然后你需要专注于调试GetFavorits WebMethod:通过调试器单步调试它并检查:你正在获取数据,它被正确序列化,响应被正确发送(对mime 类型,响应中没有额外的数据)。此外,您不需要在 ajax 请求中设置 contentType。并将该参数转换为适当的对象而不是字符串,例如{_userID: '1337'}(除非您的方法接受并反序列化 JSON 字符串 - 从代码示例中不清楚)
  • 如果我从我的 WebMethod 返回一个列表而不是一个字符串,它工作正常 :)
猜你喜欢
  • 1970-01-01
  • 2019-01-06
  • 2012-07-28
  • 2018-06-17
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多