Javascript到Microsoft SQL Server(AJAX请求) [英] Javascript to Microsoft SQL Server (AJAX request)
问题描述
我遇到问题,如何通过AJAX请求从我的javascript中选择数据库(Microsoft SQL Server)中的数据。
我知道我需要一个服务器语言,但似乎PHP无法做到这一点!
I have a problem, how can i select data from my database (Microsoft SQL Server) from my javascript by an AJAX request. I know I need a "server language", but it seems that PHP cannot do this !
我该怎么办?
谢谢!
推荐答案
PHP是服务器端语言。为PHP包创建驱动程序,允许它们与几种不同类型的数据库体系结构系统进行交互。在这种情况下, SQL Server
将通过PHP的 sqlsrv
驱动程序连接。
PHP is a server side language. Drivers are created for thee PHP package that allow them to interface with several different types of database architecture systems. In this case, the SQL Server
would be connected to through the sqlsrv
drivers for PHP.
对数据库的简单查询如下所示:
A simple query to the database looks like the following:
-- query.php --
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Person";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$name = sqlsrv_get_field( $stmt, 0);
echo $name; //maybe the name is "George"
这会建立连接,然后尝试查询数据库。由于我们只检索一行,因此我们使用 sqlsrv_fetch()
来尝试填充 $ stmt
变量。如果它有效,那么我们将获得 $ name
作为从索引 0
的列的行返回。这会将 $ name
的值返回到我们的 ajax调用的
(如下图所示)成功函数
This establishes the connection, and then attempts to query the database. As we're just retrieving one row, we use sqlsrv_fetch()
to attempt to populate the $stmt
variable. If it works, then we'll get $name
as a return from the row at column with index 0
. This will return the value of $name
to the success function
of our ajax call
(as illustrated below)
$。ajax()
很简单。弄清楚什么元素将触发ajax调用,然后就这样做..
The $.ajax()
is simple. Figure out what element is going to fire the ajax call, then just do it..
$('element').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'query.php',
type: 'GET',
success: function(data){
console.log(data); //will show George in the console
//otherwise it will show sql_srv errors.
}
});
});
资源
- sqlsrv_connect()
- sqlsrv_query()
- $.ajax()
这篇关于Javascript到Microsoft SQL Server(AJAX请求)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!