首页 > 解决方案 > 从 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>

任何想法如何从头部的函数中获取这些变量并将它们用于正文中的另一个脚本。谢谢。

标签: javascriptajax

解决方案


您只需将它们放在两个代码部分都可以访问的地方。

更高的范围是全局范围。如果您只在上面放置 2 个变量,$(document).ready(function ()它们将可以在代码的后面部分访问。然而,这是不受欢迎的。由于可能会干扰可能运行的其他 js 代码,因此污染全局范围绝不是一个好习惯。

正确的方法是找到一个方便的对象,这两个部分都可以访问。最明显的答案是document对象。

做就是了

document.latitute = emp.latitude;
document.longitude = emp.longitude;

甚至更好

document.myProject = { lat: emp.latitude, lon: emp.longitude}; 

在代码的成功部分中,并且在后面的部分中可以访问这些变量。您还可以使用任何 DOM 的节点来存储和访问变量。


推荐阅读