使用 AJAX 在 jQuery 和 C# 之间传递变量和执行事件
本文关键字:变量 执行 事件 AJAX jQuery 使用 之间 | 更新日期: 2023-09-27 18:33:17
基本上我有一段jQuery代码,它使用jqvmaps来渲染世界地图并对其执行操作:
<script type="text/javascript" lang="js">
$(document).ready(function(){
jQuery('#vmap').vectorMap(
{
map: 'world_en',
backgroundColor: '#a5bfdd',
borderColor: 'white',
borderOpacity: 0.25,
borderWidth: 1,
color: 'gray',
enableZoom: true,
hoverColor: 'orange',
hoverOpacity: null,
normalizeFunction: 'linear',
scaleColors: ['#b6d6ff', '#005ace'],
selectedColor: 'red',
selectedRegion: null,
showTooltip: true,
onRegionClick: function (element, code, region)
{
var CountryName = document.getElementById('#<%= RegionName.ClientID %>');
var CountryCode = document.getElementById('#<%= RegionCode.ClientID %>');
var CountryCapital = document.getElementById('#<%= RegionCapital.ClientID %>');
var Country = document.getElementById('#<%= RegionName.ClientID %>');
var Capital = document.getElementById('#Capital');
//var Code = document.getElementById('#Code');
var codeValue = code;
var data = { CountryCode: codeValue }
var CapitalCity = GetCapital(code);
CountryName.value = region;
CountryCode.value = code.toUpperCase();
Capital.value = CapitalCity;
Country.text= region;
Code.text = code;
}
})(jQuery);
(function GetCapital(code)
{
$.ajax({
type: "POST",
url: 'Default.aspx/GetCapital',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (code) {
alert(code.Capital)
}
});
})(jQuery);
})(jQuery);
</script>
我想做的是在单击区域时运行 C# 方法(并将参数传递给它)(在 OnRegionClick 事件内),获取返回的值并使用新信息更新标签/输入。
using System;
using System.Collections.Generic;
using System.Web.UI;
using Newtonsoft.Json;
using System.IO;
using System.Web.Services;
using System.Web.Script.Services;
namespace WorldMapDetails
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetCapital(string CountryCode)
{
//do your stuff
Country Country = new Country();
List<Country> selectedCountry = JsonConvert.DeserializeObject<List<Country>>(File.ReadAllText(@"C:'Users'Brian'Documents'Bloxinations'Bloxinations'WorldMapInfo'WorldMapDetails'Scripts'json'Countries.json"));
String Capital = null;
foreach (Country c in selectedCountry)
{
if (c.cca2 == CountryCode)
{
Capital = c.capital.ToString().ToUpper();
}
}
return Capital;
}
}
}
我尝试使用以下代码使用 [WebMethod],但它不起作用:
$.ajax({
type: "POST",
url: 'Default.aspx/GetCapital',
data: code,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (code) {
//......
}
}
});
首先,你应该获取值代码并创建一个要传递的 json,
在通过时,您应该JSON.stringify
data
var codeValue = document.getElementById('#Code').value;
var data = {countryCode: codeValue}
$.ajax({
type: "POST",
url: 'Default.aspx/GetCapital',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (code) {
//......
}
}
});