[英]How can i convert serialized collection to javascript array in Ajax
I have a code where i serailize a list in a web service and write it on the response, from there i want go get that response and convert to an array in javasript using Ajax我有一个代码,我在其中对 web 服务中的列表进行序列化并将其写入响应,从那里我希望 go 获得该响应并使用 Z3EB7106C3477A60E6BBF5DBFDE1DA 转换为 javasript 中的数组
here is webservice code这是网络服务代码
[WebMethod]
public void getLatLng() {
city = new City();
city.Lat = "-29.0882";
city.Lng = "26.2098";
all.Add(city);
//2
city = new City();
city.Lat = "-29.1032";
city.Lng = "26.1965";
all.Add(city);
//3
city = new City();
city.Lat = "-29.143";
city.Lng = "26.1803";
all.Add(city);
//4
city = new City();
city.Lat = "-29.1847";
city.Lng = "26.2393";
all.Add(city);
//4
city = new City();
city.Lat = "-29.1292";
city.Lng = "26.2526";
all.Add(city);
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(all));
}
Javascript Javascript
const area = new Array;
$.ajax({
method: "post",
url: "LatLng.asmx/getLatLng",
dataType: "json",
success: function (data) {
for (i = 0; i < data.length; i++) {
//create objects
let one = { lat: data[i].Lat, lng: data[i].Lng };
//add objects to array
area.push(one);
console.log("abc", JSON.stringify(one));
}
},
error: function (repo) {
alert("error " + repo);
}
});
Here is my web service results这是我的 web 服务结果
[{"Lat":"-29.0882","Lng":"26.2098"},{"Lat":"-29.1032","Lng":"26.1965"},{"Lat":"-29.143","Lng":"26.1803"},{"Lat":"-29.1847","Lng":"26.2393"},{"Lat":"-29.1292","Lng":"26.2526"}] [{"Lat":"-29.0882","Lng":"26.2098"},{"Lat":"-29.1032","Lng":"26.1965"},{"Lat":"-29.143"," Lng":"26.1803"},{"Lat":"-29.1847","Lng":"26.2393"},{"Lat":"-29.1292","Lng":"26.2526"}]
and i want to turn it to an array like this我想把它变成这样的数组
const area = [
{ lat: -29.0882, lng: 26.2098 },
{ lat: -29.1032, lng: 26.1965 },
{ lat: -29.143, lng: 26.1803 },
{ lat: -29.1847, lng: 26.2393 },
{ lat: -29.1292, lng: 26.2526 },
I recommend using Newtonsoft.Json
instead of the old/legaxcy JavaScriptSerializer
.我建议使用Newtonsoft.Json
而不是旧的/legaxcy JavaScriptSerializer
。 Also update your controller method to return a string:还要更新您的 controller 方法以返回一个字符串:
using Newtonsoft.Json;
...
[WebMethod]
public string getLatLng()
{
...
return JsonConvert.SerializeObject(all);
}
Update your javascript/jquery to the following:将您的 javascript/jquery 更新为以下内容:
let area = [];
$.ajax({
method: "post",
url: "LatLng.asmx/getLatLng",
dataType: "json",
success: function (response) {
data = response.d; // important for asp.net
area = JSON.parse(data);
},
error: function (repo) {
alert("error " + repo);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.