简体   繁体   中英

How do I write this JS code to retrieve JSON data from my php file?

I am trying to populate a dropdown list to select countries and also to highlight the border of that country when selected. This is for an application that displays a fullscreen map and gives you information on different countries that you select. I need to figure out how to access my json files data using php and js.

I am using a json file that looks like this:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Bahamas","iso_a2":"BS","iso_a3":"BHS","iso_n3":"044"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-77.53466,23.75975]....

I have to use a php file to pass its contents to js (becuase I can't let the json data be passed to the clients side) My php looks like this:

<?php

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

                $string = file_get_contents("/libs/js/json/countryBordersGeo.json");
    $decode = json_decode($string, true);

                $countries = [];
    foreach ($decode["features"] as $country) {
        array_push($countries, (object)["name"=> $country["properties"]["name"], "iso"=> $country["properties"]["iso_a3"],"geometry"=> $country["geometry"]["type"],"coordinates"=> $country["geometry"]["coordinates"]]);
    }
    echo json_encode($countries);
?>

I believe that my php file is correct but I am struggling to get this to all work in the js file. Currently, my js looks like this:

$(document).ready(() => {

    // Get the country information
    $.ajax({
        url: "libs/php/getCountryBorders.php",
        type: 'GET',
        data: {},
        dataType: 'json',
        success: function(data) {

            // ---------------- Generate Country Objects ----------------
          if (result.status.name == "ok") {
                
                name = result['features']['properties']['0']['name'];
                iso_a2 = result['features']['properties']['0']['iso_a2'];
                iso_a3 = result['features']['properties']['0']['iso_a3'];
                iso_n3 = result['features']['properties']['0']['iso_n3'];
                geoType = result['features']['geometry']['0']['type'];
                coordinates = result['features']['geometry']['0']['coordinates'];;.....

Would this be the correct way to write my js code? I just need to access the json data, I hope I've explained this properly. Thank you.

npm install axios

 import axios from 'axios'; axios.get('/your-php-file.php').then(response => { console.log(response.data); }).catch(error => { console.log(error); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM