这是一种从 js 中的 xmlhttp2 请求中提取 var 的方法吗?

Is it a way to extract a var from xmlhttp2 request in js?

我是 javascript 和 php 程序的新手。

我正在尝试从 xhttp2 请求中提取一个 var 以在我的代码中重用它。经过多次测试后,我找不到办法做到这一点。我想我真的不明白异步函数是如何工作的..

我的代码:

    xhttp2.onreadystatechange = function() {
 if (this.readyState == 4 && this.status ==200) {
    let response = JSON.parse(xhttp2.responseText)
   let arrond = L.geoJSON(response).addTo(map1);}
 };
 xhttp2.open("GET", "js/test3.php",true);
 xhttp2.send();

我正在尝试将“arrond”变量提取为 json

感谢您的帮助!

维克多

这是我的完整代码:它在传单项目中。 xhttp 请求用于将数据添加到我的 lealet 地图。数据来自 postgreSQL 数据库和数组的 php 代码。

    //Initialisation de la carte 
var map1 = L.map('map1');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {attribution: osmAttrib});
map1.setView([45.76, 4.85], 12);

//ajout de basemaps supplémentaires
var osmhumanUrl='https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png';
var osmhuman = new L.TileLayer(osmhumanUrl, {attribution: osmAttrib}).addTo(map1); 

var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
    attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
});

// //Appel de la couche equipement
var xhttp2 = new XMLHttpRequest();
// //lecture de la connexion au fichier php (2 variables cf. biblio)
xhttp2.onreadystatechange = function() {
     if (this.readyState == 4 && this.status ==200) {
//  //récupération du résultat de la requête sql et parcours de la couche :
      document.getElementById("demo").innerHTML =
      (xhttp2.responseText);
        let response = JSON.parse(xhttp2.responseText)
//         //appel de la couche
//      //console.log(response[0])
       let arrond = L.geoJSON(response).addTo(map1); 
     }
     };
xhttp2.open("GET", "js/test3.php",true);
xhttp2.send();


let Jardins =  L.geoJSON(jardins, 
    {
        onEachFeature: function (feature, layer) {
          layer.bindPopup(feature.properties.title);
        }
      }).addTo(map1);

//groupe de couche et de basemaps et layerControl
var baseMaps = {
    "OSM": osm,
    "OSM Humanitarian": osmhuman, 
    "Satellite": Esri_WorldImagery
};

var overlayMaps = {
    "Initiatives existantes": Jardins
};

//Ajout d'un bouton de gestion des calques
L.control.layers(baseMaps).addTo(map1);

将变量放在全局范围内而不是嵌套范围内

将其与其他全局变量(如 map1、osmUrl)一起声明

var map1 = L.map('map1');
...
let arrond; ''here declare it

//Appel de la couche equipement
var xhttp2 = new XMLHttpRequest();
//lecture de la connexion au fichier php (2 variables cf. biblio)
xhttp2.onreadystatechange = function() {
   if (this.readyState == 4 && this.status ==200) {
      //récupération du résultat de la requête sql et parcours de la couche :
      document.getElementById("demo").innerHTML =
      (xhttp2.responseText);
        let response = JSON.parse(xhttp2.responseText)
         //appel de la couche
       arrond = L.geoJSON(response).addTo(map1); here assign the new value to the variable
     }
     };
xhttp2.open("GET", "js/test3.php",true);
xhttp2.send();

外面onreadystatechange使用它

..
console.log(arrond)

编辑

我刚刚注意到您将 ajax 属性 设置为 true。所以一切都是异步的。

您可以使用主函数来获取异步操作的结果,以确保后者已经到达。您可以使用 fetch api ,与经典的 XMLHttpRequest.

相比,它在代码复杂性方面更简单
 async function getData() {
        const response = await fetch("js/test3.php");
        const data = await response.json();
        console.log(data)
        const geojson = L.geoJSON(data, {
          onEachFeature
        });
        geojson.addTo(map1);
        map1.fitBounds(geojson.getBounds());
        return geojson;
      }

然后创建一个主函数并从现在开始对 geojson 实例进行所有进一步的 json 操作:

async function main() {
            const arrond = await getData();
            console.log(arrond);
}
    
main(); // call it 

这是一个带有免费地理位置的示例json api

<!DOCTYPE html>
<html>

<head>

  <title>Quick Start - Leaflet</title>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>



</head>

<body>
  <div id="map1" style="width: 600px; height: 400px;"></div>
  <script>
    //Initialisation de la carte 
    var map1 = L.map('map1');
    var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib = 'Map data © OpenStreetMap contributors';
    var osm = new L.TileLayer(osmUrl, {
      attribution: osmAttrib
    });
    map1.setView([45.76, 4.85], 12);

    //ajout de basemaps supplémentaires
    var osmhumanUrl = 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png';
    var osmhuman = new L.TileLayer(osmhumanUrl, {
      attribution: osmAttrib
    }).addTo(map1);

    var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    });

    function onEachFeature(feature, layer) {
      // does this feature have a property named popupContent?
      if (feature.properties && feature.properties.label) {
        layer.bindPopup(feature.properties.label);
      }
    }


    async function getData() {
      const response = await fetch("https://api-adresse.data.gouv.fr/search/?q=paris&type=street");
      const data = await response.json();
      console.log(data)
      const geojson = L.geoJSON(data, {
        onEachFeature
      });
      geojson.addTo(map1);
      map1.fitBounds(geojson.getBounds());
      return geojson;
    }

    async function main() {
      const arrond = await getData();
      console.log(arrond);
    }

    main();
  </script>

</body>

</html>