是否可以在java脚本中将通用地址列表传递给客户端?
列表数据可以在服务器端获得,我想将列表发送到java脚本函数,该函数将获得所有地址的地理编码,然后将列表返回给服务器端。
这里我到目前为止尝试过,不知道如何在javascript函数中读取列表然后将结果返回给服务器。
Private Shared Function CreateGenericArray() As List(Of AddressInfo)
Dim _AddressInfo As New List(Of AddressInfo)()
Dim lp As New AddressInfo()
lp.AddressID = 1
lp.AddressLine1 = "My Address"
lp.City = "PA"
lp.PostalCode = "11654"
_AddressInfo.Add(lp)
Return _AddressInfo
End Function
Public Sub ConvertToJSON()
Dim jss1 As New JavaScriptSerializer()
Dim _myJSONstring As String = jss1.Serialize(CreateGenericArray())
Dim player As String = (Convert.ToString("var player=") & _myJSONstring) + ";"
Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "player123", player, True)
End Sub
<form id="form1" runat="server">
<script type="text/javascript">
$(player).each(function (index, person) {
alert('AddressID: ' + person.AddressID +
' AddressLine1: ' + person.AddressLine1 +
' City: ' + person.City
);
});
</script>
</form>
答案 0 :(得分:3)
我将使用C#
而不是Visual Basic,但你基本上可以这样做:
代码背后:
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Address> deserialize = serializer.Deserialize<List<Address>>(address);
foreach(Address address in deserialize)
{
// Do something with Exposed Properties:
}
Address Class
将是非常非常基本的:
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
这基本上就是后端,现在你需要在前端做的就是:
function BuildAddress(Id, Street, City, State, Zip) {
var address = null;
item = {
Id: Id,
Street: Street,
City: City,
State: State,
Zip: Zip
};
}
构建我们对象的干净函数。现在,我们实际上需要传递这些内容:
var address = new Array();
var convertAddress;
address.push(BuildAddress(id, street, city, state, zip));
convertedAddress = JSON.stringfy(address);
$.ajax({
url: '<%= Page.ResolveUrl("~/Services/Location.aspx") %>'
data: { Address: convertedAddress},
type: 'POST',
success: function (address) {
var result = JSON.parse(address);
// Do something with result, example: result[0].City
}
});
这将以您尝试的方式传递数据。你不得不稍微玩一下。