weixin_33701251 2018-08-28 13:29 采纳率: 0%
浏览 62

从JS获取变量

I have following code in <head> which has variables (emp.longitude and emp.longitude) which I need to get:

<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>

In a <body> a have another script where I need to use those variables:

<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>

I already have a table which outputs those values in a <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>

Any ideas how can I get those variables from function in a head and use them in another script in a body. Thanks.

  • 写回答

2条回答 默认 最新

  • weixin_33691817 2018-08-28 13:31
    关注

    Assign the values to var and they will be hoisted.

    var latitude = 0;
    var longitude = 0;
    

    later in your fetch,

    latitude = emp.latitude;
    longitude = emp.longtitude;
    

    If you do not you have to do as the comments say and create a special function to get the values. You can use hoisting here, and as long as you are not doing this "a lot" you'll be fine, regardless of the polluting the namespace.

    评论

报告相同问题?