JSON data is asynchronously bound to the table of the interface and automatically refreshes the principle and code

Time:2021-10-18

I’m used to WinForm. Everyone is used to setting the way of datasource.
If you want to refresh the page regularly, it is actually very easy to implement the encapsulated UpdatePanel and timer controls with. Net. This adds many elements you can’t control. For example, after using UpdatePanel, the style you set may change, and then you need to adjust these. So it’s better to use some code with high self-control.

Today, let’s start with the example of automatic page refresh with UpdatePanel and timer.
First, let’s take a look at my general processing program. In this program, I find out the DataTable from the database, and then convert it into JSON and transmit it to the client

Copy codeThe code is as follows:
/// <summary>
///Summary description of GetData
/// </summary>
public class getData : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = “text/plain”;
//context.Response.Write(“Hello World”);
//Set query string
string strSql = “select ckrID,chrCarNumber,cncName,bcrName from T_CarNumberCategory,T_CheckResult,t_BusinessCategory where ckrcheckresult is null and cncID=ckrcarnumbercategoryid and ckrBusinessCategory=bcrID”;
//Set connection string
string strConn = “Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.24.173)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User Id=admin;Password=123123”;
//Define and open a database connection
OracleConnection conn = new OracleConnection(strConn);
conn.Open();
//Define command line objects,
OracleCommand cmd = new OracleCommand(strSql, conn);
//Define an adapter to fill the DataTable;
OracleDataAdapter adp = new OracleDataAdapter(cmd);
//Define a DataTable and populate it with an adapter
DataTable dt = new DataTable();
adp.Fill(dt);
context.Response.Write(JsonConvert.SerializeObject(dt));
//The above is the DataTable I queried from the database, and then use a JSON operation class library to convert it to JSON
////Since you don’t have a database environment, I copy the above string for your test experiment
////Since the copy is in double quotation marks, an error will be reported here, so I changed it to single quotation marks
////However, when the client obtains JSON, it recognizes double quotation marks, so it has to replace them again… heart-broken
//Var JSON = “[{ckrid ‘:’1359374764563’, ‘chrcarnumber’:’123123 ‘,’ cncname ‘:’large vehicle’, ‘bcrname’:’approval and inspection mark ‘}, {ckrid’:’1359371470153 ‘,’ chrcarnumber ‘:’asdfsadf’, ‘cncname’:’large vehicle ‘,’ bcrname ‘:’registration’}, {ckrid ‘:’1359343210678’, ‘chrcarnumber’:’111222 ‘,’ CNAME ‘:’large vehicle’, ‘bcrname’:’registration ‘}, {‘ckrid’:’1359354395618 ‘,’ chrcarnumber ‘:’123asd’, ‘cncname’:’large vehicle ‘,’ bcrname ‘:’registration’}, {‘ckrid’:’1359355217314 ‘,’ chrcarnumber ‘:’123asdqwe’, ‘cncname’:’large vehicle ‘,’ bcrname ‘:’registration’}, {‘ckrid’:’1359355356271 ‘,’ chrcarnumber ‘:’1111111’, ‘cncname’:’large vehicle ‘,’ bcrname ‘:’registration’}, {‘ckrid’:’1359355490374 ‘,’ chrcrnumber ‘:’123123123’, ‘cncname’:’large vehicle ‘,’ bcrname ‘:’registration’}, {‘ckrid’:’1358074597852 ‘,’ chrcrnumber ‘:’323232’, ‘cncncname’:’embassy vehicle ‘,’ bcrname ‘:’approved inspection mark’}] “;
//context.Response.Write(json.Replace(‘\”,’\”‘));
}
public bool IsReusable
{
get
{
return false;
}
}
}

The notes in the server-side program above are very detailed. If you don’t understand, you can leave a message to explain. The class library uses newtonsoft.json.dll. You can click to download from my online disk – no cost ~ Pro

Here is the client code

Copy codeThe code is as follows:
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
< title > test < / Title >
<script src=”jquery-1.7.1.js” type=”text/javascript”></script>
</head>
<body>
<form runat=”server”>
<table>
<tr>
<td>
Serial number
</td>
<td>
license plate number
</td>
<td>
Business type
</td>
<td>
<input type=”button” value=”button” />
</td>
</tr>
</table>
<div>
Loading data
</div>
<script type=”text/jscript”>
//Simulate what a data is loading
setTimeout(function () { $(“#loading”).hide(); }, 1000);
//Set the timer to call the method regularly. The unit is milliseconds
setInterval(SetData(), 1000);
//Get the data from the server and display it on the interface, which is implemented by getjson method
function SetData() {
$.getJSON(“getData.ashx”, null, function (obj) {
$(“tr”).eq(0).nextAll().remove(); // Delete tr except for template line
//Dynamically load the obtained data into the table
for (var i = 0; i < obj.length; i++) {
//Set the ID of the fourth bar to red (this can be used to modify the style according to the content)
if (i == 3) {
row.find(“#ID”).css(“color”, “red”);
}
//Get the template line and copy one line
var row = $(“#tem”).clone();
//Add a new row of buttons to the click event
row.find(“#btn input”).click({ name: obj[i].CHRCARNUMBER, back: obj[i].CKRID }, operation);
//Note: in jQuery 1.4.2, the above method will make mistakes. I don’t know the specific reason. Anyway, there is no problem in writing 1.7.1
//If the above code doesn’t work, you can try it
//row.find(“#btn input”).bind(“click”,{ name: obj[i].CHRCARNUMBER, back: obj[i].CKRID }, operation);
//Personally test that the above code can run in 1.4.2. Min.. The solution of this problem wastes a long time, and the older framework is used
row.find(“#ID”).text(obj[i].CKRID); // Serial number
row.find(“#CarNumber”).text(obj[i].CHRCARNUMBER); // Car license plate number
row.find(“#BusinessName”).text(obj[i].BCRNAME); // Name of business handled
//Add a new row to the table
row.appendTo(“#data”);
}
});
}
//Get the passed parameters and display them
function operation(event) {
alert(event.data.name);
alert(event.data.back);
}
//Get the data from the server and display it on the interface, which is implemented by Ajax
function SetDataByAjax() {
$.ajax({
Type: “get”, / / set the call type
Datatype: “JSON”, / / set the data type
url: “getData.ashx”, //url
complete: function () { $(“#loading”).hide() },
success: function (obj) {
$(“tr”).eq(0).nextAll().remove(); // Delete tr except for template line
//Dynamically load the obtained data into the table
for (var i = 0; i < obj.length; i++) {
//Set the ID of the fourth bar to red (this can be used to modify the style according to the content)
if (i == 3) {
row.find(“#ID”).css(“color”, “red”);
}
//Get the template line and copy one line
var row = $(“#tem”).clone();
//Add a new row of buttons to the click event
row.find(“#btn input”).click({ name: obj[i].CHRCARNUMBER, back: obj[i].CKRID }, operation);
//Note: in jQuery 1.4.2, the above method will make mistakes. I don’t know the specific reason. Anyway, there is no problem in writing 1.7.1
//If the above code doesn’t work, you can try it
//row.find(“#btn input”).bind(“click”,{ name: obj[i].CHRCARNUMBER, back: obj[i].CKRID }, operation);
//The above code can be run in 1.4.2. The solution of this problem wastes a long time. It is strange to use the older framework
row.find(“#ID”).text(obj[i].CKRID); // Serial number
row.find(“#CarNumber”).text(obj[i].CHRCARNUMBER); // Car license plate number
row.find(“#BusinessName”).text(obj[i].BCRNAME); // Name of business handled
//Add a new row to the table
row.appendTo(“#data”);
}
}
});
}
</script>
</form>
</body>
</html>

The above is an example of self writing an automatic page refresh. In the above example, you can’t control anything except jQuery. If you’re good enough, you don’t want to use his framework and want to write one yourself, then it’s OK. Just for me, a beginner, I can save a lot of things with this.

A getjson method only needs to give three parameters, and it will give you all the operations such as creating objects, callback functions and setting parameters. This is still worth learning. In normal learning, we should consider refining the commonly used things into a method and putting them into our own small code base.

Although the above code is not very difficult, I personally feel that this is a milestone example of my understanding of Ajax, an example that has solved many of my doubts.

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]