jquery ajax json 综合应用实例
通过AJAX异步减少网络内容传输,而JSON则可以把传输内容缩减到纯数据;然后利用jQuery内置的AJAX功能直接获得JSON格式的数据;在客户端直接绑定到数据控件里面,从而达到最优。
1.设计htm页面
<code class="html"> <title>test2</title> <script language="javascript" type="text/javascript" src="js/jquery-latest.pack.js"></script> <script language="javascript" type="text/javascript" src="js/PageDate.js"></script> <div> <div> <br> <input id="first" type="button" value=" << "><input id="previous" type="button" value=" < "><input id="next" type="button" value=" > "><input id="last" type="button" value=" >> "> <span id="pageinfo"></span> <ul id="datas"> <li id="template"> <span id="OrderID"> 订单ID </span>/ <span id="CustomerID"> 客户ID </span> <span id="EmployeeID"> 雇员ID </span>/ <span id="OrderDate"> 订购日期 </span>/ <span id="ShippedDate"> 发货日期 </span>/ <span id="ShippedName"> 货主名称 </span>/ <span id="ShippedAddress"> 货主地址 </span>/ <span id="ShippedCity"> 货主城市 </span>/ <span id="more"> 更多信息 </span> </li> </ul> </div> <div id="load" style="left: 0px; position: absolute; top: 0px; background-color: red"> LOADING.... </div> <input type="hidden" id="pagecount"> </div> ////注:ID属性比较重要,用于数据绑定。</code>
2.使用jQuery编写AJAX请求文件
<code class="javascript">var pageIndex = 1 var pageCount = 0; $(function() { GetPageCount(); //取得分页总数 pageCount = parseInt($("#pagecount").val()); //分页总数放到变量pageCount里 $("#load").hide(); //隐藏loading提示 $("#template").hide(); //隐藏模板 ChangeState(0, 1); //设置翻页按钮的初始状态 bind(); //绑定第一页的数据 //第一页按钮click事件 $("#first").click(function() { pageIndex = 1; ChangeState(0, 1); bind(); }); //上一页按钮click事件 $("#previous").click(function() { pageIndex -= 1; ChangeState( - 1, 1); if (pageIndex = pageCount) { pageIndex = pageCount; ChangeState( - 1, 0); } bind(pageIndex); }); //最后一页按钮click事件 $("#last").click(function() { pageIndex = pageCount; ChangeState(1, 0); bind(pageIndex); }); }); //AJAX方法取得数据并显示到页面上 function bind() { $("[@id=ready]").remove(); $("#load").show(); $.ajax({ type: "get", //使用get方法访问后台 dataType: "json", //返回json格式的数据 url: "Handler.ashx", //要访问的后台地址 data: "pageIndex=" + pageIndex, //要发送的数据 complete: function() { $("#load").hide(); }, //AJAX请求完成时隐藏loading提示 success: function(msg) { //msg为返回的数据,在这里做数据绑定 var data = msg.table; $.each(data, function(i, n) { var row = $("#template").clone(); row.find("#OrderID").text(n.OrderID); row.find("#CustomerID").text(n.CustomerID); row.find("#EmployeeID").text(n.EmployeeID); row.find("#OrderDate").text(ChangeDate(n.OrderDate)); if (n.RequiredDate !== undefined) row.find("#ShippedDate").text(ChangeDate(n.RequiredDate)); row.find("#ShippedName").text(n.ShipName); row.find("#ShippedAddress").text(n.ShipAddress); row.find("#ShippedCity").text(n.ShipCity); row.find("#more").html("<a href="OrderInfo.aspx?id=%22" n.orderid pageindex> More</a>"); row.attr("id", "ready"); //改变绑定好数据的行的id row.appendTo("#datas"); //添加到模板的容器中 }); $("[@id=ready]").show(); SetPageInfo(); } }); } function ChangeDate(date) { return date.replace("-", "/").replace("-", "/"); } //设置第几页/共几页的信息 function SetPageInfo() { $("#pageinfo").html(pageIndex + "/" + pageCount); } //AJAX方法取得分页总数 function GetPageCount() { $.ajax({ type: "get", dataType: "text", url: "Handler.ashx", data: "getPageCount=1", async: false, success: function(msg) { $("#pagecount").val(msg); } }); } //改变翻页按钮状态 function ChangeState(state1, state2) { if (state1 == 1) { document.getElementById("first").disabled = ""; document.getElementById("previous").disabled = ""; } else if (state1 == 0) { document.getElementById("first").disabled = "disabled"; document.getElementById("previous").disabled = "disabled"; } if (state2 == 1) { document.getElementById("next").disabled = ""; document.getElementById("last").disabled = ""; } else if (state2 == 0) { document.getElementById("next").disabled = "disabled"; document.getElementById("last").disabled = "disabled"; } }</code>
3.利用JSON三方控件在服务器端获取JSON格式数据
<code class="cs"> using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Configuration; using System.Data.SqlClient; using System.Text; using System.Xml; using NetServ.Net.Json; namespace jQueryJSON { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/json/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Handler : IHttpHandler { readonly int PageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"]); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //不让浏览器缓存 context.Response.Buffer = true; context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); context.Response.AddHeader("pragma", "no-cache"); context.Response.AddHeader("cache-control", ""); context.Response.CacheControl = "no-cache"; string result = ""; if (context.Request.Params["getPageCount"] != null) result = GetPageCount(); if (context.Request.Params["pageIndex"] != null) { string pageindex = context.Request.Params["pageIndex"]; result = GetPageData(context.Request.Params["pageIndex"]); } context.Response.Write(result); } private string GetPageData(string p) { int PageIndex = int.Parse(p); string sql; if (PageIndex == 1) sql = "select top " + PageSize.ToString() + " * from Orders order by OrderID desc"; else sql = "select top " + PageSize.ToString() + " * from Orders where OrderID not in(select top " + ((PageIndex - 1) * PageSize).ToString() + " OrderID from Orders order by OrderID desc) order by OrderID desc"; string dbfile = ConfigurationManager.ConnectionStrings["conn"].ToString(); SqlConnection conn = new SqlConnection(dbfile); SqlDataAdapter da = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable("table"); da.Fill(dt); return DataTableJson(dt); } private string GetPageCount() { string dbfile = ConfigurationManager.ConnectionStrings["conn"].ToString(); SqlConnection conn = new SqlConnection(dbfile); SqlCommand cmd = new SqlCommand("select count(*) from Orders", conn); conn.Open(); int rowcount = Convert.ToInt32(cmd.ExecuteScalar()); conn.Close(); return ((rowcount + PageSize - 1) / PageSize).ToString(); } private string DataTable2Json(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{\""); jsonBuilder.Append(dt.TableName); jsonBuilder.Append("\":["); for (int i = 0; i </code>
以上是jquery ajax json 综合应用实例。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

JSON (JavaScriptObjectNotation) is a lightweight data exchange format commonly used for data exchange between web applications. When processing JSON data, we often encounter Unicode-encoded Chinese characters (such as "u4e2du6587") and need to convert them into readable Chinese characters. In PHP, we can achieve this conversion through some simple methods. Next, we will detail how to convert JSONUnico
