d3.js — я не могу получить данные, созданные с помощью php json с d3.json

Я разработал приложение php (data1.php), которое производит вывод json из MySQL:

PHP

$username = "alitest";
$password = "aliden07";
$host = "localhost";
$database="ali_app";

$server = mysqli_connect($host, $username, $password);
$connection = mysqli_select_db($server,$database);

$myquery = "select Letter as  '\"Letter\"', CAST(Freq as unsigned) as '\"Freq\"' from datajson";
$query = mysqli_query($server,$myquery);

if ( ! $query ) {
echo mysqli_error();
die;
}

$data = array();

for ($x = 0; $x < mysqli_num_rows($query); $x++) {
$data[] = mysqli_fetch_assoc($query);
}

header('Content-type:application/json;charset=utf-8');
echo json_encode($data,JSON_NUMERIC_CHECK);

mysqli_close($server);

В HTML-файл я хочу получить данные JSON с помощью команды d3.json. Я изготовлю гистограмму с возвращенными данными.

HTML с JS и CSS

<!DOCTYPE html>
<meta charset="utf-8">

<head>
<style>
.bar{
fill: steelblue;
}

.bar:hover{
fill: brown;
}

.axis {
font: 10px sans-serif;
}

.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
// set the dimensions of the canvas
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;// set the ranges
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);

// define the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);

// add the SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// load the data
d3.json("http://localhost:8081/php/data1.php", function(error, data) {

data.forEach(function(d) {
d.Letter = d.Letter;
d.Freq = +d.Freq;
});

// scale the range of the data
x.domain(data.map(function(d) { return d.Letter; }));
y.domain([0, d3.max(data, function(d) { return d.Freq; })]);

// add axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)" );

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 5)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");

// Add bar chart
svg.selectAll("bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d.Letter);
})
.attr("width", x.rangeBand())
.attr("y", function(d) {
return y(d.Freq);
})
.attr("height", function(d) {
return height - y(d.Freq);
});
});

</script>
</body>

Я попытался запустить приложение с двумя серверами http (servez и npm установить http-server -g).

Для обслуживания php у меня установлен wamp сервер.
Когда я изменяю ввод команды d3.json на локальный файл, он работает, но когда я даю ссылку на файл php, я не вижу диаграмму.

// load the data
d3.json("data1_db_out1.json", function(error, data) {

data.forEach(function(d) {
d.Letter = d.Letter;
d.Freq = +d.Freq;
});

Я пробую их на своем рабочем столе.

  • http-сервер: localhost: 8080
  • wamp: localhost 8081

Любая помощь будет оценена.

1

Решение

Это может быть проблема перекрестного происхождения. Попробуйте включить CORS в своем ответе json:

header("Access-Control-Allow-Origin: *");
0

Другие решения

Это то, что я получаю, когда бегу HTTP: // локальный: 8081 / PHP / data1.php на wamp сервере:

[
{
Буква А»,
Частота: 25
},
{
Буква: «Б»,
Частота: 12
},
{
Буква: «С»,
Частота 47
},
{
Буква: «Д»,
Частота: 34
},
{
Буква: «Е»,
Freq: 54
},
{
Буква: «F»,
Частота: 21
},
{
Буква: «G»,
Частота: 57
},
{
Буква: «Н»,
Частота: 31
},
{
Письмо: «Я»,
Частота: 17
},
{
Письмо: «J»,
Freq: 5
},
{
Письмо: «К»,
Частота 23
},
{
Буква: «L»,
Частота: 39
},
{
Буква: «М»,
Частота: 29
},
{
Буква: «Н»,
Частота: 33
},
{
Письмо: «О»,
Частота: 18
},
{
Буква: «П»,
Частота: 35
},
{
Письмо: «Q»,
Частота: 11
},
{
Буква: «Р»,
Freq: 45
},
{
Буквы»,
Частота 43
},
{
Буква: «Т»,
Freq: 28
},
{
Буква: «U»,
Частота: 26
},
{
Буква: «V»,
Частота: 30
},
{
Буква: «Х»,
Freq: 5
},
{
Буква: «Y»,
Частота: 4
},
{
Буква: «Z»,
Частота: 2
}
]
0

И я изменил строку запроса в data1.php. Текущая текущая версия:

<?php
$username = "alitest";
$password = "aliden07";
$host = "localhost";
$database="ali_app";

$server = mysqli_connect($host, $username, $password);
$connection = mysqli_select_db($server,$database);

//$myquery = "select Letter as  '\"Letter\"', CAST(Freq as unsigned) as '\"Freq\"' from datajson";
$myquery = "select Letter , CAST(Freq as unsigned) as Freq  from datajson";
$query = mysqli_query($server,$myquery);

if ( ! $query ) {
echo mysqli_error();
die;
}

$data = array();

for ($x = 0; $x < mysqli_num_rows($query); $x++) {
$data[] = mysqli_fetch_assoc($query);
}

//header('Content-type:application/json;charset=utf-8');
header("Access-Control-Allow-Origin: *");
echo json_encode($data,JSON_NUMERIC_CHECK);

mysqli_close($server);
?>
0