javascript - 从 JS 获取变量
问题描述
我有以下代码,其中有我需要获取<head>
的变量(emp.longitude
和):emp.longitude
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
async: false,
url: 'GetRecords.asmx/GetValues',
dataType: "json",
method: 'post',
success: function (data) {
var employeeTable = $('#tblEmployee tbody');
employeeTable.empty();
$(data).each(function (index, emp) {
employeeTable.append('</td><td>'
+ emp.latitude + '</td><td>' + emp.longitude + '</td><td>');
});
},
error: function (err) {
alert(err +" fail");
}
});
});
</script>
在一个<body>
我需要使用这些变量的另一个脚本中:
<script>
var mymap = L.map('mapid').setView([38.8, -94.8], 5);
// need to use them below (longitude and latitude)
L.marker([longitude,latitude], { icon: truckIcon }).addTo(mymap).bindPopup("I am here!");
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
</script>
我已经有一个表格,可以将这些值输出到<body>
<form id="form1" runat="server">
<div class="container">
<h3 class="text-uppercase text-center">How to retrive data using ajax in asp.net</h3>
<table id="tblEmployee" class="table table-bordered">
<thead class="bg-primary text-white">
<tr>
<th>latitude</th>
<th>longitude</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</form>
任何想法如何从头部的函数中获取这些变量并将它们用于正文中的另一个脚本。谢谢。
解决方案
您只需将它们放在两个代码部分都可以访问的地方。
更高的范围是全局范围。如果您只在上面放置 2 个变量,$(document).ready(function ()
它们将可以在代码的后面部分访问。然而,这是不受欢迎的。由于可能会干扰可能运行的其他 js 代码,因此污染全局范围绝不是一个好习惯。
正确的方法是找到一个方便的对象,这两个部分都可以访问。最明显的答案是document
对象。
做就是了
document.latitute = emp.latitude;
document.longitude = emp.longitude;
甚至更好
document.myProject = { lat: emp.latitude, lon: emp.longitude};
在代码的成功部分中,并且在后面的部分中可以访问这些变量。您还可以使用任何 DOM 的节点来存储和访问变量。
推荐阅读
- python - 如何通过在__init__中获取用户输入来使用类计算矩形的面积
- java - 基于条件Java获取可选
- apache - OpenSSL 升级 - CentOS 7
- c++ - 来自 Steam 社区市场的 Curl 数据
- html - 当我尝试通过实时服务器运行 html 代码时,它显示服务器在端口 5500 启动,但未能在浏览器预览中打开
- c# - 如何使用 jmespath 对 ASC 和 DESC 进行排序
- android - 在 Android 上的多个片段上请求蓝牙适配器对象是否安全?
- javascript - 如何使用打字稿删除数组重复?
- javascript - 无法用 javascript 填充输入
- dgrid - dgrid 从 0.3 更新 - 值得吗?