您好,欢迎访问一九零五行业门户网

介绍jquery中$.getJSON的使用方法

jquery.getjson(url, [data], [callback])
通过 http get 请求载入 json 数据。
参数:
url,[data],[callback]                          string,map,functionv1.0
url : 发送请求地址。
data : 待发送 key/value 参数。
callback : 载入成功时回调函数。
getjson的使用方法 jquery.getjson(url,[data],[callback])
要获得一个json文件的内容,就可以使用$.getjson()方法,这个方法会在取得相应文件后对文件进行处理,并将处理得到的javascript对象提供给代码.
回调函数提供了一种等候数据返回的方式,而不是立即执行代码,回调函数也需要一个参数,该参数中保存着返回的数据。这样我们就可能使用jquery提供的另一个全局函数(类方法).each()来实现循环操作,将.getjson函数返回的每组数据循环处理。
提供一个servlet写的小例子:
package com.servlet; import java.io.ioexception; import java.io.printwriter; import java.util.arraylist; import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import net.sf.json.jsonarray; import com.entity.city; /** * @author administrator * 返回json字符串 * * 这里是用传统方法做的一个简单列子! * 整合struts,这种写法也能实现,但struts2已经实现了json,比这个写法方便 * */ public class getjsonservlet extends httpservlet { public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this.dopost(request, response); } public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcharacterencoding("utf-8"); printwriter out = response.getwriter(); /*返回一个list集合来绑定下拉框*/ list<city> list = new arraylist<city>(); list.add(new city(1,"aaaa")); list.add(new city(2,"bbbb")); list.add(new city(3,"cccc")); list.add(new city(4,"dddd")); //获取集合的json字符串 jsonarray json = jsonarray.fromobject(list); system.out.println(json.tostring()); //打印结果: //[{"id":1,"name":"aaaa"},{"id":2,"name":"bbbb"},{"id":3,"name":"cccc"},{"id":4,"name":"dddd"}] out.print(json.tostring()); out.flush(); out.close(); } }
jsp页面代码:
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <title>my jsp 'index.jsp' starting page</title> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> //初始加载页面时 $(document).ready(function(){ alert("加载.............."); var city=$("#city");//下拉框 $.getjson("getjsonservlet",function(data){ //通过循环取出data里面的值 $.each(data,function(i,value){ var tempoption = document.createelement("option"); tempoption.value = value.id; tempoption.innerhtml = value.name; city.append(tempoption); }); }); }); </script> </head> <body> <select id="city"> <option>==选择==</option> </select> </body> </html>
实体类就俩属性:
private integer id; private string name;
以上能实现在页面加载的时候,把内容绑定到下拉框!
通过打印流,是ajax常用的方法!
需要的代码的可以下载    getjson download   下载代码
以上就是介绍jquery中$.getjson的使用方法的详细内容。
其它类似信息

推荐信息