Database field: ID (primary key, auto-increment), name (commodity name), price (commodity unit price)
Add a dataset datasetproducts. Add method: getdatabyname ()
-----> Corresponding SQL:
Select ID, name, price from DBO. t_product
Where name = @ name
Create a general handler: getprice. ashx
Code:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using ajax. datasetproductstableadapters;
Namespace Ajax
{
/// <Summary>
/// Summary of getprice
/// </Summary>
Public class getprice: ihttphandler
{
Public void processrequest (httpcontext context)
{
Context. response. contenttype = "text/plain ";
String name = context. request ["name"];
VaR DATA = new t_producttableadapter (). getdatabyname (name); // call the method in Dataset
If (data. Count <= 0)
{
Context. response. Write ("None | 0"); // the left side of the vertical line is the return status, and the right side is the price
}
Else
{
Context. response. Write ("OK |" + data. Single (). Price); // you can replace the custom protocol format "OK" with other strings;
}
}
Public bool isreusable
{
Get
{
Return false;
}
}
}
}
HTML page code:
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Ajax query price </title>
<SCRIPT src = "scripts/jquery-1.4.1.js" type = "text/JavaScript"> </SCRIPT>
<Script language = "JavaScript" type = "text/JavaScript">
$ (Function (){
$ ("# Text1"). Blur (function (){
VaR name = $ ("# text1"). Val ();
$. Post ("getprice. ashx", {"name": name}, function (data, statustext ){
If (statustext = "success "){
VaR ATTS = data. Split ("| ");
If (ATTS [0] = "OK") {// ATTS [0] is a parameter, indicating the status;
$ ("# Text2"). Val (ATTS [1]); // ATTS [1] is a parameter, indicating the price;
} Else if (ATTS [0] = "NONE "){
$ ("# Text2"). Val ("This item is not available ");
} Else {
Alert ("Returned format error ");
}
} Else {
Alert ("ajax error! ");
}
});
});
});
</SCRIPT>
</Head>
<Body>
Query name: <input id = "text1" type = "text"/> <br/>
<Br/>
Price & nbsp; format: <input id = "text2" type = "text"/>
</Body>
</Html>