[英]How can i convert serialized collection to javascript array in Ajax
我有一個代碼,我在其中對 web 服務中的列表進行序列化並將其寫入響應,從那里我希望 go 獲得該響應並使用 Z3EB7106C3477A60E6BBF5DBFDE1DA 轉換為 javasript 中的數組
這是網絡服務代碼
[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
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);
}
});
這是我的 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"}]
我想把它變成這樣的數組
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 },
我建議使用Newtonsoft.Json
而不是舊的/legaxcy JavaScriptSerializer
。 還要更新您的 controller 方法以返回一個字符串:
using Newtonsoft.Json;
...
[WebMethod]
public string getLatLng()
{
...
return JsonConvert.SerializeObject(all);
}
將您的 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.