gpt4 book ai didi

javascript - 是否有获取 JSON 数据的 ASP.NET 样板方式?

转载 作者:行者123 更新时间:2023-11-30 07:52:36 28 4
gpt4 key购买 nike

我目前正在尝试这个,但我一直看到可怕的错误:

Unexpected token o in JSON at position 1

enter image description here

我正在努力寻找解决方案,想知道是否有人对如何解决这个问题有任何建议?

被序列化为 JSON 的类:

[Serializable]
public class GeoCoordinate
{
public GeoCoordinate()
{
}

[JsonProperty(PropertyName = "lat")]
public double Latitude { get; }

[JsonProperty(PropertyName = "long")]
public double Longitude { get; }

public GeoCoordinate(double latitude, double longitude)
{
Latitude = latitude;
Longitude = longitude;
}

public override string ToString()
{
return string.Format("{0},{1}", Latitude, Longitude);
}
}

Ajax 调用:

function getLocationData() {
jQuery.ajax({
url: abp.appPath + "Home/GetLocationsAsync",
type: "GET",
dataType: "json",
async: true,
success: function (data) {
var myArray = jQuery.parseJSON(data);
locations = [];
$.each(myArray, function (index, element) {
locations.push([element.lat, element.long]);
});
}
});
}

Controller :

[HttpGet]
public async Task<JsonResult> GetLocationsAsync()
{
var cords = await _practiceAppService.GetAllGeoCoordinates();
return Json(cords);
}

应用服务:

public async Task<IList<GeoCoordinate>> GetAllGeoCoordinates()
{
var geoCoordinates = await Repository.GetAll()
.Where(x => !x.Disabled && !x.Latitude.Equals(0) && !x.Longitude.Equals(0))
.Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
.ToListAsync();

return geoCoordinates;
}

Console.log 尝试调用 parseJSON 之前的数据:

console.log(data);
var myArray = jQuery.parseJSON(data);

enter image description here

最佳答案

巧合的是,有一个部分叫做The ASP.NET Boilerplate Way这正是解决这个问题的方法。

请注意,只有第 2 点是 ABP 特有的:

  1. GetLocationsAsync 返回一个 JSON 对象而不是字符串,因此您不应调用 parseJSON .

    您可以重现错误消息:jQuery.parseJSON({});

  2. ABP 包装JsonResult。来自 AJAX Return Messages 上的文档:

    This return format is recognized and handled by the abp.ajax function.

    您可以使用 [DontWrapResult] 属性,但您也可以在这里利用 ABP。 abp.ajax handles the display of error messages如果您抛出 UserFriendlyException

  3. 由于 ajax 是异步的,getLocationData 不能直接返回 locations

    您可以返回链式 Promise .如果您不熟悉 Promises,请阅读 Using Promises首先。

  4. 有一种比 $.eachpush 更简洁的方法。

    您可以使用 map .

最后:

function getLocationData() {
return abp.ajax({
url: abp.appPath + "Home/GetLocationsAsync",
type: 'GET'
}).then(function (result) {
return result.map(function (element) {
return [element.lat, element.long];
});
});
}

用法:

getLocationData().then(function (locations) {
console.log(locations);
});

关于javascript - 是否有获取 JSON 数据的 ASP.NET 样板方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49423775/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com