jquery+ajax取得並操作json資料(附代碼)
這次帶給大家jquery ajax取得並操作json資料(附程式碼),jquery ajax取得並操作json資料的注意事項有哪些,以下就是實戰案例,一起來看一下。
對於問題從後台獲取json數據,將內容填充到下拉列表,程式碼非常簡單,具體過程請看下面程式碼。
需求:url:連結 par:ID sel:下拉清單選擇器
//取得下拉清單
#function BuildSelectBox(url, par, sel) { $(sel).empty(); $.getJSON(url, { id: par }, function (json, textStatus) { for (var i = json.length - 1; i >= 0; i--) { $(sel).prepend('<option value="' + json[i].Id + '">' + json[i].Name + '</option>') }; $(sel).prepend('<option value="0">请选择</option>') }); }
<!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 src="JS/jquery-1.8.0.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $.ajax({ url: 'jsondata.ashx', type: 'GET', dataType: 'json', timeout: 1000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { $("#list").html('加载中...'); } function erryFunction() { alert("error"); } function succFunction(tt) { $("#list").html(''); //eval将字符串转成对象数组 //var json = { "id": "10086", "uname": "zhangsan", "email": "zhangsan@qq.com" }; //json = eval(json); //alert("===json:id=" + json.id + ",uname=" + json.uname + ",email=" + json.email); var json = eval(tt); //数组 $.each(json, function (index, item) { //循环获取数据 var name = json[index].Name; var idnumber = json[index].IdNumber; var sex = json[index].Sex; $("#list").html($("#list").html() + "<br>" + name + " - " + idnumber + " - " + sex + "<br/>"); }); } }); </script> </head> <body> <ul id="list"> </ul> </body> </html> <%@ WebHandler Language="C#" Class="jsondata" %> using System; using System.Web; using System.Web.Script.Serialization; using System.IO; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; using System.Data; public class jsondata : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string JsonStr = JsonConvert.SerializeObject(CreateDT()); context.Response.Write(JsonStr); context.Response.End(); } #region 创建测试数据源 //创建DataTable protected DataTable CreateDT() { DataTable tblDatas = new DataTable("Datas"); //序号列 //tblDatas.Columns.Add("ID", Type.GetType("System.Int32")); //tblDatas.Columns[0].AutoIncrement = true; //tblDatas.Columns[0].AutoIncrementSeed = 1; //tblDatas.Columns[0].AutoIncrementStep = 1; //数据列 tblDatas.Columns.Add("IdNumber", Type.GetType("System.String")); tblDatas.Columns.Add("Name", Type.GetType("System.String")); tblDatas.Columns.Add("BirthDate", Type.GetType("System.String")); tblDatas.Columns.Add("Sex", Type.GetType("System.String")); tblDatas.Columns.Add("Wage", Type.GetType("System.Decimal")); tblDatas.Columns.Add("Bonus", Type.GetType("System.Decimal")); //统计列开始 tblDatas.Columns.Add("NeedPay", Type.GetType("System.String"), "Wage+Bonus"); //统计列结束 tblDatas.Columns.Add("Address", Type.GetType("System.String")); tblDatas.Columns.Add("PostCode", Type.GetType("System.String")); //设置身份证号码为主键 tblDatas.PrimaryKey = new DataColumn[] { tblDatas.Columns["IdNumber"] }; tblDatas.Rows.Add(new object[] { "43100000000000", "张三", "1982", "0", 3000, 1000, null, "深圳市", "518000" }); tblDatas.Rows.Add(new object[] { "43100000000001", "李四", "1983", "1", 3500, 1200, null, "深圳市", "518000" }); tblDatas.Rows.Add(new object[] { "43100000000002", "王五", "1984", "1", 4000, 1300, null, "深圳市", "518000" }); tblDatas.Rows.Add(new object[] { "43100000000003", "赵六", "1985", "0", 5000, 1400, null, "深圳市", "518000" }); tblDatas.Rows.Add(new object[] { "43100000000004", "牛七", "1986", "1", 6000, 1500, null, "深圳市", "518000" }); return tblDatas; } #endregion public bool IsReusable { get { return false; } } } <!-- <script type="text/javascript"> $(function () { $.ajax({ url: 'jsondata.ashx', type: 'GET', dataType: 'json', timeout: 1000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { $("#list").html('加载中...'); } function erryFunction() { alert("error"); } function succFunction(tt) { $("#list").html(''); //eval将字符串转成对象数组 //var json = { "id": "10086", "uname": "zhangsan", "email": "zhangsan@qq.com" }; //json = eval(json); //alert("===json:id=" + json.id + ",uname=" + json.uname + ",email=" + json.email); var json = eval(tt); //数组 $.each(json, function (index, item) { //循环获取数据 var Key = json[index].key; var Info = json[index].info; // var idnumber = json[index].IdNumber; // var sex = json[index].Sex; $("#list").html($("#list").html() + "<br>" + Key + "----" + Info.name); //+ " - " + idnumber + " - " + sex + "<br/>"); }); } }); </script> --> <%@ WebHandler Language="C#" Class="jsondata" %> using System; using System.Web; using System.Web.Script.Serialization; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Data; public class jsondata : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Cache.SetNoStore(); string data = "[{\"key\":\"1\",\"info\":{\"name\":\"222\",\"age\":\"333\",\"sex\":\"444\"}},{\"key\":\"2\",\"info\":{\"name\":\"999\",\"age\":\"000\",\"sex\":\"111\"}}]"; context.Response.Write(new JavaScriptSerializer().Serialize(data)); } public bool IsReusable { get { return false; } } } <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test2013.aspx.cs" Inherits="Test2013" %> <!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 runat="server"> <title></title> <script src="JS/jquery-1.8.0.min.js" type="text/javascript"></script> <script type="text/javascript"> function GetPara(o) { var sortid = $(o).val(); $.ajax({ url: 'GetPara.ashx?type=get&sortid=' + sortid, type: 'GET', dataType: 'json', timeout: 3000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { $("#list").html('加载中...'); } function erryFunction() { alert("error"); } function succFunction(tt) { $("#list").html(''); var json = eval(tt); //数组 $.each(json, function (index, item) { //循环获取数据 var Id = json[index].id; var Name = json[index].name; $("#list").html($("#list").html() + "<br>" + Name + "<input type='text' id='" + Id + "' /><br/>"); }); } }; function SavePara() { var parameter = {}; $("#list input:text").each(function () { var key = $(this).attr("id"); var value = $(this).val(); parameter[key] = value; }); $.ajax({ url: 'GetPara.ashx?type=save', type: 'POST', dataType: 'json', data: parameter, timeout: 3000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { } function erryFunction() { } function succFunction(tt) { } }; </script> </head> <body> <form id="form1" runat="server"> <p> <asp:DropDownList ID="ddl1" runat="server" onchange="GetPara(this)"> </asp:DropDownList> <ul id="list"></ul> <input type="button" value="保存数据" onclick="SavePara()" /> </p> </form> </body> </html> <%@ WebHandler Language="C#" Class="GetPara" %> using System; using System.Web; using System.Data; using System.Collections.Generic; using System.Web.Script.Serialization; public class GetPara : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string SortId = context.Request["sortid"]; string Type = context.Request["type"]; if (Type=="get") { if (!string.IsNullOrEmpty(SortId)) { DataTable dt = MSCL.SqlHelper.GetDataTable("select * from PR_PRODUCTPARAS where sortid='" + SortId + "' "); List<Paras> list = new List<Paras>(); for (int i = 0; i < dt.Rows.Count; i++) { Paras a = new Paras(); a.id = dt.Rows[i]["PARAID"].ToString(); a.name = dt.Rows[i]["PARANAME"].ToString(); list.Add(a); } context.Response.Write(new JavaScriptSerializer().Serialize(list)); } } else if (Type == "save") { //反序列化json System.IO.Stream stream = context.Request.InputStream; System.IO.StreamReader sr = new System.IO.StreamReader(stream, System.Text.Encoding.GetEncoding("UTF-8")); string sJson = sr.ReadToEnd(); if (sJson.Contains("&")) { string[] sArr = sJson.Split('&'); for (int i = 0; i < sArr.Length; i++) { string[] sArr1 = sArr[i].Split('='); object id = sArr1[0]; object value = sArr1[1]; } } } else { } } public bool IsReusable { get { return false; } } public struct Paras { public string id; public string name; } }
Jquery 使用Ajax取得後台返回的Json資料頁面處理過程
具體實作過程請看下面程式碼範例:
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章! 推薦閱讀:
以上是jquery+ajax取得並操作json資料(附代碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP數組轉JSON的效能最佳化方法包括:使用JSON擴充和json_encode()函數;新增JSON_UNESCAPED_UNICODE選項以避免字元轉義;使用緩衝區提高循環編碼效能;快取JSON編碼結果;考慮使用第三方JSON編碼庫。

MySQL5.7和MySQL8.0是兩個不同的MySQL資料庫版本,它們之間有以下一些主要差異:效能改進:MySQL8.0相對於MySQL5.7有一些效能改進。其中包括更好的查詢優化器、更有效率的查詢執行計劃產生、更好的索引演算法和平行查詢等。這些改進可以提高查詢效能和整體系統效能。 JSON支援:MySQL8.0引入了對JSON資料類型的原生支持,包括JSON資料的儲存、查詢和索引。這使得在MySQL中處理和操作JSON資料變得更加方便和有效率。事務特性:MySQL8.0引進了一些新的事務特性,如原子

Jackson庫中的註解可控制JSON序列化和反序列化:序列化:@JsonIgnore:忽略屬性@JsonProperty:指定名稱@JsonGetter:使用獲取方法@JsonSetter:使用設定方法反序列化:@JsonIgnoreProperties:忽略屬性@ JsonProperty:指定名稱@JsonCreator:使用建構子@JsonDeserialize:自訂邏輯

快速入門:Pandas讀取JSON檔案的方法,需要具體程式碼範例引言:在資料分析和資料科學領域,Pandas是一個重要的Python庫之一。它提供了豐富的功能和靈活的資料結構,能夠方便地對各種資料進行處理和分析。在實際應用中,我們經常會遇到需要讀取JSON檔案的情況。本文將介紹如何使用Pandas來讀取JSON文件,並附上特定的程式碼範例。一、Pandas的安裝

JavaScript教學:如何取得HTTP狀態碼,需要具體程式碼範例前言:在Web開發中,經常會涉及到與伺服器進行資料互動的場景。在與伺服器進行通訊時,我們經常需要取得傳回的HTTP狀態碼來判斷操作是否成功,並根據不同的狀態碼來進行對應的處理。本篇文章將教你如何使用JavaScript來取得HTTP狀態碼,並提供一些實用的程式碼範例。使用XMLHttpRequest

深入了解PHP:JSONUnicode轉中文的實作方法在開發中,我們經常會遇到需要處理JSON資料的情況,而JSON中的Unicode編碼在一些場景下會為我們帶來一些問題,特別是當需要將Unicode編碼轉換為中文字元時。在PHP中,有一些方法可以幫助我們實現這個轉換過程,以下將介紹常用的方法,並提供具體的程式碼範例。首先,讓我們先來了解一下JSON中Un

JavaScript中的HTTP狀態碼取得方法簡介:在進行前端開發中,我們常常需要處理與後端介面的交互,而HTTP狀態碼就是其中非常重要的一部分。了解並取得HTTP狀態碼有助於我們更好地處理介面傳回的資料。本文將介紹使用JavaScript取得HTTP狀態碼的方法,並提供具體程式碼範例。一、什麼是HTTP狀態碼HTTP狀態碼是指當瀏覽器向伺服器發起請求時,服務

PHP提供了以下函數來處理JSON資料:解析JSON資料:使用json_decode()將JSON字串轉換為PHP數組。建立JSON資料:使用json_encode()將PHP陣列或物件轉換為JSON字串。取得JSON資料的特定值:使用PHP數組函數存取特定值,例如鍵值對或陣列元素。
