您的位置:首页 > Web前端 > JQuery

boboJQuery实现Ajax 根据商品名称自动显示价格

2014-07-08 17:52 501 查看
数据库字段:Id(主键,自增),Name(商品名称),Price(商品单价)

添加数据集DataSetProducts ,添加方法:GetDataByName()

----->对应SQL:

SELECT id, name, price FROM dbo.T_Product
where name = @name

新建一般处理程序:GetPrice.ashx

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AJAX.DataSetProductsTableAdapters;

namespace AJAX
{
/// <summary>
/// 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); //调用DataSet中的方法
if (data.Count <= 0)
{
context.Response.Write("none|0"); //竖线左边是返回状态,右边是价格
}
else
{
context.Response.Write("ok|" + data.Single().price); //我们自己定义的协议格式 ok可以换成其他的字符串;
}
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

Html页面代码:

<!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完成查询价格</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]是参数;表示状态;
$("#Text2").val(atts[1]); //atts[1]是参数,表示价格;
} else if (atts[0] == "none") {
$("#Text2").val("没有这个商品");
} else {
alert("返回格式错误");
}
} else {
alert("Ajax错误!");
}
});
});
});
</script>
</head>
<body>
查询名称:<input id="Text1" type="text" /><br />
<br />
价        格:<input id="Text2" type="text" />
</body>
</html>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: