我通过PHP脚本连接到SQL服务器并显示在浏览器上检索的内容。
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
href="http://cdn.sencha.com/ext/trial/5.0.0/build/packages/ext-theme-neptune/build/resources/ext-
theme-neptune-all.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/php" src="connection.php"></script>
</head>
<body>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function() {
d3.json("connection.php", function (data) {
document.write(data);
});
});
connection.php
<?php
// Server Name
$myServer = "10.112.1.2";
// Database
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"logs", "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($myServer, $connectionInfo);
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$sql = "SELECT * FROM dbo.logsData";
$data = sqlsrv_query( $conn, $sql );
if( $data === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
所有3个文件都在同一个文件夹中。 浏览器只显示一个null,我没有从.php文件中点击任何日志信息。我的方法对吗?我使用正确的javascript事件吗?
答案 0 :(得分:0)
以这种方式更改你的connection.php:
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
header('Content-Type: application/json');
}
您需要更改响应的mime类型。此外,除了json数据,你不能打印出任何其他内容。这就是我从代码中删除这些内容的方式:
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
答案 1 :(得分:-1)
尝试在此处使用connection.php的相对路径名: d3.json(&#34; 连接。 php &#34;
类似&#34; /dirname/connection.php"。
您可以使用完整路径名单独测试connection.php,例如http://www.yourserver.xxx/dirname1/dirname2/...connection.php