ajax的数据库,AJAX数据库

AJAX Database 例子

AJAX can be used for interactive communication with a database.

AJAX数据库 例子

The following example will demonstrate how a web page can fetch

information from a database with AJAX:

例子

Select a customer:

Alfreds Futterkiste

North/South

Wolski Zajazd

Customer info will be listed here...

例子 Explained - The showCustomer() 函数

When a user selects a customer in the dropdown list above, a function called showCustomer() is executed. The

function is triggered by the onchange event:

showCustomer

function showCustomer(str) {

if (str == "") {

document.getElementById("txtHint").innerHTML = "";

return;

}

const xhttp = new XMLHttpRequest();

xhttp.onload = function() {

document.getElementById("txtHint").innerHTML = this.responseText;

}

xhttp.open("GET", "getcustomer.php?q="+str);

xhttp.send();

}

The showCustomer() function does the following:

Check if a customer is selected

Create an XMLHttpRequest object

Create the function to be executed when the server response is ready

Send the request off to a file on the server

Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The AJAX Server Page

The page on the server called by the JavaScript above is a PHP file called "getcustomer.php".

The source code in "getcustomer.php" runs a query against a database, and returns the result in an HTML

table:

$mysqli = new mysqli("servername", "username",

"password", "dbname");

if($mysqli->connect_error) {

exit('Could not connect');

}

$sql = "SELECT customerid, companyname,

contactname, address, city, postalcode, country

FROM customers WHERE

customerid = ?";

$stmt = $mysqli->prepare($sql);

$stmt->bind_param("s", $_GET['q']);

$stmt->execute();

$stmt->store_result();

$stmt->bind_result($cid,

$cname, $name, $adr, $city, $pcode, $country);

$stmt->fetch();

$stmt->close();

echo "

echo "

";

echo "

CustomerID";

echo

"

" . $cid . "";

echo "

CompanyName";

echo "

" . $cname

. "

";

echo "

ContactName";

echo "

" . $name . "";

echo "

Address";

echo "

" .

$adr . "

";

echo "

City";

echo "

" . $city . "";

echo "

PostalCode";

echo "

" .

$pcode . "

";

echo "

Country";

echo "

" . $country .

"

";

echo "

";

echo "

";

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值