簡體   English   中英

如何將數據從sql傳輸到javascript?

[英]How to transfer data from sql to javascript?

我使用以下示例: https : //www.sitepoint.com/dynamic-geo-maps-svg-jquery/但我需要從MySql DB獲取數據。

我有2個主要文件:1)map.php(連接到數據庫並顯示svg地圖)2)map.js(顯示帶有靜態數據的彩色地圖)

在JS文件中,我看到以下行:

enter code here
var regions=[
    {
        "region_name": "Lombardia",
        "region_code": "lom",
        "population": 9794525
    },
    {
        "region_name": "Campania",
        "region_code": "cam",
        "population": 5769750
    },
    // etc ...
];

我需要將區域名稱的值從db更改為值。 但是我不怎么樣?

在我的PHP主要變量是:

echo "Region: ".$row['region_name']."
echo "Code of region: ".$row['region_code']."
echo "Value: ".$row['value']."

通常,您不會修改js文件。 相反,您需要使用ajax調用從數據庫加載數據,然后將其“提供”給您使用的控件。 為此,您需要一個返回數據的Web服務和一些調用它的javascript函數。 您可以執行以下操作:

var jqxhr = $.get( "map.php", function() {
  alert( "success" );
}).done(function(data ) {
    refresh_your_map(data);
});

檢查https://api.jquery.com/jquery.get/了解更多詳細信息

編輯-做這樣的事情:

/* define this function in your js file*/
var getRegionsData = function()
{
    var result =[];
    $.ajax({ url: 'map.php', 
       async: false,
       dataType: 'json',
       success: function(data) {
          result = data;
       }
    });
    return result;
}

//then do this 
var regions=getRegionsData();
//the rest of your code from map.js

首先,您的PHP代碼應該連接到數據庫,提取您感興趣的數據,並從中構建一個json字符串,就像示例中的regions數據一樣。 您的PHP將返回此json。 您可能想使用json,因為它是最ajax / js友好的格式。

您的JS代碼應對該PHP進行Ajax調用,以獲取json格式的數據。 假設您正在使用jquery,它是這樣的:

$.ajax({
    url : "map.php",
    dataType : "json",
    done: function(data){
       // the data parameter is the json returned by the php
       // already converted to javascript object...
       // Just like the regions array from your example.
    }
});

有關jquery ajax api的更多信息和選項,請參見http://api.jquery.com/jquery.ajax

index.php

enter code here
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="map.css" rel="stylesheet" media="all">
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script src="map.js"></script>
<title>Моя карта</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "happy_user";
$password = "1234567890";
$dbname = "freesite_zzz_com_ua";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT region_name, region_code, value FROM map";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "region_name: " . $row["region_name"]. " region_code: " .          
$row["region_code"]. " value: " . $row["value"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

<h1>svg map</h1>

<div class="map">

<svg version="1.1" id="map_x5F_id" xmlns="http://www.w3.org/2000/svg"     
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 width="595.3px" height="841.9px" viewBox="0 0 595.3 841.9" style="enable-        
background:new 0 0 595.3 841.9;" xml:space="preserve"
>

<g id="id_x5F_1">
<rect x="58" y="163" width="85" height="85"/>
</g>
<g id="id_x5F_2">
<rect x="143" y="163" width="85" height="85"/>
</g>
<g id="id_x5F_3">
<rect x="228.1" y="163" width="85" height="85"/>
</g>
</svg>
</div>
</body>
</html>

map.js:

var regions=[
{
    "region_name": "region-1",
    "region_code": "id_x5F_1",
    "value": "10"
},
{
    "region_name": "region-2",
    "region_code": "id_x5F_2",
    "value": "20"
},
{
    "region_name": "region-3",
    "region_code": "id_x5F_3",
    "value": "30"
}
];

var temp_array = regions.map(function(item){
return item.value;
});

var highest_value = Math.max.apply(Math, temp_array);

$(function() {

for(i = 0; i < regions.length; i++) {

    $('#'+ regions[i].region_code)
    .css({'fill': 'rgba(11, 104, 170,' + regions[i].value/highest_value     
+')'})
    .data('region', regions[i]);
}

$('.map g').mouseover(function (e) {
    var region_data=$(this).data('region');
    $('<div class="info_panel">'+
        region_data.region_name + '<br>' +
        'value: ' + region_data.value.toLocaleString("en-UK") +
        '</div>'
     )
    .appendTo('body');
})
.mouseleave(function () {
    $('.info_panel').remove();
})
.mousemove(function(e) {
    var mouseX = e.pageX, //X coordinates of mouse
        mouseY = e.pageY; //Y coordinates of mouse

    $('.info_panel').css({
        top: mouseY-50,
        left: mouseX - ($('.info_panel').width()/2)
    });
});
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM