2014-11-03 66 views
0

我通過PHP腳本連接到SQL服務器並顯示在瀏覽器中檢索到的內容。通過PHP連接到數據庫並在瀏覽器上顯示內容

的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

裹一切都在一個try/catch(http://php.net/manual/en/language.exceptions.php)如果你的PHP,這將告訴你。 ini設置隱藏了一些錯誤。 – 2014-11-03 08:29:09

+0

其他一切看起來不錯?我如何測試單獨的連接? – Natasha 2014-11-03 08:35:04

+0

如果您只想檢查與連接對象關聯的值,請使用[var_dump](http://php.net/manual/en/function.var-dump.php)。 – 2014-11-04 03:12:35

回答

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>"; 
相關問題