简单的ajax获取json

前端之家收集整理的这篇文章主要介绍了简单的ajax获取json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一个DBhelper类,用来操作数据库

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.sqlClient;

namespace JsonTest.helper
{
public class DBhelper
{
public static string ConnectStrings;

public static void GetConnectStr()
{
ConnectStrings = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStr"].ConnectionString;
}
public static sqlDataReader GetCommentByID(int id,string sql)
{
GetConnectStr();
sqlDataReader rs = null;
try
{
sqlConnection con = new sqlConnection(ConnectStrings);
con.Open();
sqlCommand com = new sqlCommand(sql,con);
rs=com.ExecuteReader();
}
catch (Exception err)
{
throw err;
}
return rs;
}
}
};

前台htm页发出ajax post请求

<!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></title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#button1").click(function sys() {
$.post("html_1.ashx",{ "ID": 1 },function sys(json) {
var str = json.item1 + json.item2 + json.item3 + json.item4;
$("ul").append("<li>" + str + "</li>");
},"json");
});
});
</script>
</head>
<body>
<input type="button" id="button1" value="点击" />
<ul>
</ul>
</body>
</html>

后台ashx处理程序处理请求

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.sqlClient;
using JsonTest.helper;
using System.Web.Script.Serialization;

namespace JsonTest
{
/// <summary>
/// html_1 的摘要说明
/// </summary>
public class html_1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
int id = Convert.ToInt32(context.Request["ID"]);
string sql = "select * from item where ItemID=" + id + "";
sqlDataReader sdr = null;
sdr=DBhelper.GetCommentByID(id,sql);
item Item = new item();
while (sdr.Read())
{

Item.item1 = sdr[0].ToString();
Item.item2 = sdr[1].ToString();
Item.item3 = sdr[2].ToString();
Item.item4 = sdr[3].ToString();
}
sdr.Close();
sdr = null;
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(Item).ToString();
context.Response.Write(json);
}

public bool IsReusable
{
get
{
return false;
}
}

public class item
{
public string item1;
public string item2;
public string item3;
public string item4;
}
}
}

这样就可以无刷新的实现

原文链接:https://www.f2er.com/ajax/165863.html

猜你在找的Ajax相关文章