JSON-结果数据未定义。如何获取JSON-数据?

JSON-data get undefined as result. How to get JSON-data?

我有一个包含位置数据的数据集。在 GetLocation 中,数据被转换为纬度和经度值。那很好用。但是当我回到 html 页面时。数据未定义。是什么原因?我该如何使用 JSon-data?

解决这个问题?
[HttpGet]
        public JsonResult GetLocation(Dictionary<string, string> items)
        {

                var result = "{ 'latitude': '" + latitude + "', 'longitude': '" + longitude + "'}";
                return Json(result);
            }

在html:

    if (item.Location == null) {
        $.ajax({
            url: "@Url.Action("GetLocation", "Home")",
            dataType: "json",
            data: { items: item },
            type: "GET",
            success: (function (data) {
                location = JSON.parse(data);
            })
        });

        console.log("location:");
        console.log(location);

请按如下更改

在 MVC return 中输入:

return Json(new { result = result }, JsonRequestBehavior.AllowGet);

在 JQuery AJAX

location = JSON.parse(data.result);

您在此处对 JSON 进行了双重编码。操作方法中的 Json() 函数将字符串编码为 JSON,这意味着 Javascript 将收到类似这样的内容(请注意整个内容的引号):

"{ 'latitude': '50.69093', 'longitude': '4.337744'}"

你应该改为这样做:

return Json(new { latitude, longitude }, JsonRequestBehavior.AllowGet);

现在在您的成功函数中,您将能够访问以下值:

success: (function (data) {
    location = JSON.parse(data);
    console.log(location.latitude);
})

另请注意 JsonRequestBehavior.AllowGet 的添加,请参阅 here 了解为什么需要它。