搜索
首页web前端js教程jquery用ajax方式从后台获取json数据后如何将内容填充到下拉列表_jquery

对于问题从后台获取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>')
 });
}

以上代码很简单吧,此问题很easy的解决了。

 Jquery 使用Ajax获取后台返回的Json数据页面处理过程

具体实现过程请看下面代码示例:

<!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&#63;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&#63;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"> 
 <div> 
  <asp:DropDownList ID="ddl1" runat="server" onchange="GetPara(this)"> 
  </asp:DropDownList> 
  <ul id="list"></ul> 
  <input type="button" value="保存数据" onclick="SavePara()" /> 
 </div> 
 </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; 
 } 
}

以上就是本文的全部内容,希望大家喜欢。

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架:为现代网络开发提供动力JavaScript框架:为现代网络开发提供动力May 02, 2025 am 12:04 AM

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

JavaScript,C和浏览器之间的关系JavaScript,C和浏览器之间的关系May 01, 2025 am 12:06 AM

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。