【问题标题】:Read JsonResult in javascript from webservice in asp.net c#从asp.net c#中的webservice读取javascript中的JsonResult
【发布时间】:2015-07-22 19:06:17
【问题描述】:

我正在尝试在 javascript 中读取 json 结果,但它给了我错误。

它在 var jsonObj = JSON.parse(msg); 上给了我错误。 错误:Uncaught SyntaxError: Unexpected token o 当我调试代码 Webservice 返回完美的 json 数据时,它在 ajax 中的成功事件上给出错误。 我如何遍历这个 json 对象?任何帮助表示赞赏。

<script type="text/javascript">

        var ProductCategoryList;

        function callpageload() {
            $.ajax({
                type: "GET",
                url: "WebService1.asmx/GetCategoryList",
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                    var jsonObj = JSON.parse(msg);
                },
                error: function (msg) {

                }
            });
        }

</script>

网络服务代码

public string GetCategoryList()
        {
            DataSet ds = Persistance.GetCategoryList();
            List<ProductCategories> prodlst = new List<ProductCategories>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ProductCategories prod = new ProductCategories();
                    prod.pid = ds.Tables[0].Rows[i]["pid"].ToString();
                    prod.id = ds.Tables[0].Rows[i]["id"].ToString();
                    prod.name = ds.Tables[0].Rows[i]["name"].ToString();
                    prodlst.Add(prod);
                }

            }
            string json = JsonConvert.SerializeObject(prodlst.ToArray());
            return json;
        }

【问题讨论】:

  • 什么错误?我没有看到任何错误。
  • 为您的 ajax 设置选项 dataType: 'json' 。我认为你不需要解析响应,因为它已经是 json 格式。

标签: javascript asp.net ajax json web-services


【解决方案1】:

尝试解析msg.d。 也使用 POST;更安全。

【讨论】:

    【解决方案2】:

    嘿,我遇到了类似的问题。对我来说,我也在使用 JQuery。

    代替你的

    var jsonObj = JSON.parse(msg);
    

    尝试使用

    var jsonObj = $.parseJSON(msg);
    

    我建议检查的另一件事是在您的 c# 端放置一个断点,以确保在使用 newtonsoft JSONconvert 时没有异常或错误。这发生了很多次,它返回一个空的 json 字符串。

    如果这有帮助,请告诉我。

    有人在我的代码中某处做过 var JSON={} 所以就报错了。

    【讨论】:

    • $.parseJSON 使用 JSON.parse 如果它可用,所以......这不太可能有任何效果。
    • Jquery 版本对我有用。所以我只是在这里发布了我的经验。
    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    相关资源
    最近更新 更多