W3.JS 数据服务器

动态数据

上一章中使用的数据是从服务器获取的静态数据。

从数据库中获取动态数据的服务器代码可以用许多不同的语言编写。

以下是一些实例:


服务器运行 PHP 和 MySQL

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("myServer", "user", "pass", "myDB");

$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
  if ($outp != "") {$outp .= ",";}
  $outp .= '{"Name":"'  . $rs["CompanyName"] . '",';
  $outp .= '"City":"'   . $rs["City"]        . '",';
  $outp .= '"Country":"'. $rs["Country"]     . '"}';
}
$outp ='{"customers":['.$outp.']}';

$conn->close();

echo($outp);
?>

跨站点的 HTTP 请求

来自不同服务器(除了请求页面)的数据请求称为跨站点 HTTP 请求。

跨站点请求在 web 上很常见。许多页面从不同的服务器加载 css、图像或脚本。

然而,在现代浏览器中,出于安全原因,脚本的 HTTP 请求被限制在同一个站点。

下面一行(在上面的 PHP 示例中)允许从跨站点访问页面:

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

服务器运行 Node.js 和 MySQL

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  var sql = require("mssql");
  var config = {user:'user', password:'pass', server:'myServer', database:'myDB'};
  sql.connect(config, function (err) {
    if (err) console.log(err);
    var request = new sql.Request();
    request.query('SELECT CompanyName, City, Country FROM Customers', function (err, recordset) {
      if (err) console.log(err)
      res.send(recordset);
    });
  });
});

var server = app.listen(5000, function () {
console.log('Server is running..');
});

服务器运行 ASP.NET, Razor 和 SQL Lite

@{
Response.AppendHeader("Access-Control-Allow-Origin", "*")
Response.AppendHeader("Content-type", "application/json")
var db = Database.Open("myDB");
var query = db.Query("SELECT CompanyName, City, Country FROM Customers");
var outp =""
var c = chr(34)
}

@foreach(var row in query)
{
if outp <> "" then outp = outp + ","
outp = outp + "{" + c + "Name"    + c + ":" + c + @row.CompanyName + c + ","
outp = outp +       c + "City"    + c + ":" + c + @row.City        + c + ","
outp = outp +       c + "Country" + c + ":" + c + @row.Country     + c + "}"
}
outp ="{" + c + "customers" + c + ":[" + outp + "]}"
@outp

服务器运行 PHP 和 MS Access

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=ISO-8859-1");

$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=myDB.mdb");

$rs = $conn->execute("SELECT CompanyName, City, Country FROM Customers");

$outp = "";
while (!$rs->EOF) {
  if ($outp != "") {$outp .= ",";}
  $outp .= '{"Name":"'  . $rs["CompanyName"] . '",';
  $outp .= '"City":"'   . $rs["City"]        . '",';
  $outp .= '"Country":"'. $rs["Country"]     . '"}';
  $rs->MoveNext();
}
$outp ='{"customers":['.$outp.']}';

$conn->close();
echo ($outp);
?>

服务器运行 ASP.NET, VB 和 MS Access

<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb"%>

<%
Response.AppendHeader("Access-Control-Allow-Origin", "*")
Response.AppendHeader("Content-type", "application/json")

Dim conn As OleDbConnection
Dim objAdapter As OleDbDataAdapter
Dim objTable As DataTable
Dim objRow As DataRow
Dim objDataSet As New DataSet()
Dim outp
Dim c

conn = New OledbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=myDB.mdb")
objAdapter = New OledbDataAdapter("SELECT CompanyName, City, Country FROM Customers", conn)
objAdapter.Fill(objDataSet, "myTable")
objTable=objDataSet.Tables("myTable")

outp = ""
c = chr(34)
for each x in objTable.Rows
if outp <> "" then outp = outp & ","
outp = outp & "{" & c & "Name"    & c & ":" & c & x("CompanyName") & c & ","
outp = outp &       c & "City"    & c & ":" & c & x("City")        & c & ","
outp = outp &       c & "Country" & c & ":" & c & x("Country")     & c & "}"
next
outp ="{" & c & "customers" & c & ":[" & outp & "]}"

conn.close
response.write(outp)
%>