ajax获取数据库数据(ajax获取数据两种类型)

今天给各位分享ajax获取数据库数据的知识,其中也会对ajax获取数据两种类型进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

怎么使用ajax为 datatables 获取数据

dataTables是一种很好用前端表格显示库。当加载大量数据时,可以用Ajax 获取数据来提高效率,增速网页加载速率。下面以一个例子作示范。

首先,需要下载jquery以及dataTables库。这里使用的是版本是jQuery v1.11.3和DataTables 1.10.9。下载网址:。

先上网页的代码。要注意的是,table中的thead和tbody必须要有。

[html] view plaincopy

!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""

html

meta http-equiv="Content-Type" content="text/html; charset=UTF-8"

head

link href="" rel="stylesheet"

titledataTable example/title

script type="text/javascript" src="jquery.js"/script

script type="text/javascript" src="jquery.dataTables.js"/script

script type="text/javascript"

$(document).ready(function() {

$("#datatable").dataTable({

"processing" : true,

"serverSide" : true,

"paginationType":"full_numbers",

"ajax" : "load",

"columns" : [

{"data" : "id"},

{"data" : "firstName"},

{"data" : "lastName"}

]

});

});

/script

style

h2{

text-align:center;

}

div {

float: left;

margin: 10px;

padding: 4px;

}

a{

margin:5px;

}

table,tr,td,th{

border:2px solid #3aec7b;

border-collapse:collapse;

}

/style

/head

body

TABLE id="datatable"

THEAD

tr

thID/th

thFirst Name/th

thLast Name/th

/tr

/THEAD

tbody

/tbody

/TABLE

/body

/html

当网页加载的时候,ajax发出请求,如下所示。

[html] view plaincopy

draw=[1]

columns[0][data]=[id]

columns[0][name]=[]

columns[0][searchable]=[true]

columns[0][orderable]=[false]

columns[0][search][value]=[]

columns[0][search][regex]=[false]

columns[1][data]=[firstName]

columns[1][name]=[]

columns[1][searchable]=[true]

columns[1][orderable]=[true]

columns[1][search][value]=[]

columns[1][search][regex]=[false]

columns[2][data]=[lastName]

columns[2][name]=[]

columns[2][searchable]=[true]

columns[2][orderable]=[true]

columns[2][search][value]=[]

columns[2][search][regex]=[false]

order[0][column]=[0]

order[0][dir]=[asc]

start=[0]

length=[10]

search[value]=[]

search[regex]=[false]

_=[1441278114568]

其中,draw是请求的序号,start是数据的偏移量,length是需要返回的最大数据条数。search[value]是查找的值。

服务端采用java的servlet完成。为简单起见,这里直接采用继承HttpServlet的方式实现。数据本应该从数据库中提取,但这里为了

简单,生成了静态数据集合作为数据源。每次请求都从集合中查找匹配的数据,然后转换成JSON返回。JSON库采用阿里的fastjson。

代码如下所示。

[java] view plaincopy

package jspTest;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Enumeration;

import java.util.LinkedList;

import java.util.Random;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import java.util.List;

import java.util.Map;

/**

* Servlet implementation class DataLoad

*/

public class DataLoad extends HttpServlet {

private static final long serialVersionUID = 1L;

static class Person {

private long id;

private String firstName;

private String lastName;

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public boolean match(String pattern) {

return firstName.contains(pattern) || lastName.contains(pattern) || Long.toString(id).contains(pattern);

}

}

private static Random r = new Random();

private static ListPerson ps = new ArrayListPerson();

static {

int size = 2512;

for (int k = 0; k size; ++k)

ps.add(generatePerson());

}

static Person generatePerson() {

Person p = new Person();

p.setId(ps.size() + 1);

p.setFirstName(generateName());

p.setLastName(generateName());

return p;

}

private static String generateName() {

StringBuilder sb = new StringBuilder();

sb.append((char) (r.nextInt(26) + 'A'));

int len = 2 + r.nextInt(4);

for (int k = 0; k len; ++k)

sb.append((char) (r.nextInt(26) + 'a'));

return sb.toString();

}

private ListPersonresult;

public ListPersongetResult(){

return result;

}

/**

* @see HttpServlet#HttpServlet()

*/

public DataLoad() {

super();

}

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int start=0;

int length=10;

String pattern="";

String draw="1";

MapString,String[]params=request.getParameterMap();

for(String attr:params.keySet()){

String[] val=params.get(attr);

System.out.println(attr+"="+Arrays.toString(val));

if(attr.equals("start"))

start=Integer.parseInt(val[0]);

if(attr.equals("length"))

length=Integer.parseInt(val[0]);

if(attr.equals("search[value]"))

pattern=val[0];

if(attr.equals("draw"))

draw=val[0];

}

int total=filter(start, length, pattern);

JSONObject obj = new JSONObject();

obj.put("draw", draw);

obj.put("recordsTotal", ps.size());

obj.put("recordsFiltered", total);

System.out.println(obj.toJSONString());

obj.put("data", result);

response.getWriter().println(obj.toJSONString());

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

private int filter(int start,int length,String pattern){

result=new LinkedListPerson();

int total=0;

for(Person s:ps){

if(!s.match(pattern))

continue;

++total;

if(start--0)

continue;

if(length--=0)

continue;

result.add(s);

}

return total;

}

public static void main(String[] rags) {

System.out.println(JSON.toJSONString(ps));

DataLoad load=new DataLoad();

load.filter(0, 10, "");

System.out.println(JSON.toJSONString(load.getResult()));

load.filter(0, 10, "a");

System.out.println(JSON.toJSONString(load.getResult()));

load.filter(10, 10, "a");

System.out.println(JSON.toJSONString(load.getResult()));

load.filter(20, 10, "a");

System.out.println(JSON.toJSONString(load.getResult()));

}

}

服务端返回的JSON数据如下所示。其中draw是请求中的draw参数,data是表格中的数据。recordsFiltered是过滤后的数据总数,recordsTotal是原始数据总数。

[html] view plaincopy

{"recordsFiltered":2512,

"data":[{"firstName":"Bzf","id":1,"lastName":"Hazkm"},{"firstName":"Imxi","id":2,"lastName":"Oieb"},{"firstName":"Glyag","id":3,"lastName":"Gvqlf"},{"firstName":"Lwbhl","id":4,"lastName":"Fvvf"},{"firstName":"Audds","id":5,"lastName":"Seunp"},{"firstName":"Otbrq","id":6,"lastName":"Hnal"},{"firstName":"Loji","id":7,"lastName":"Qicn"},{"firstName":"Rjy","id":8,"lastName":"Emrygr"},{"firstName":"Gcglkd","id":9,"lastName":"Ldgrs"},{"firstName":"Txh","id":10,"lastName":"Qwe"}],

"draw":"1",

"recordsTotal":2512}

jsp中,用ajax获取数据

jsp中用ajax获取数据的例子如下:

jsp代码:

%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%

%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

html

HEAD

TITLE留学生系统/TITLE

META http-equiv=Content-Type content="text/html; charset=GBK"

SCRIPT language=JavaScript type=text/JavaScript

var XMLHttpReq = false;

//ajax接口

function createXMLHttpRequest(){

if(window.XMLHttpRequest){

XMLHttpReq = new XMLHttpRequest();

}else if(window.ActiveXObject){

try{

XMLHttpReq = new ActiveXObject("MSXML2.XMLHTTP");

}catch(e){

try{

XMLHttpReq = new ActiveXObject("Mircsoft.XMLHTTP");

}catch(e1){}

}

}

}

function sendRequest(url){

createXMLHttpRequest();

XMLHttpReq.open("GET",url,true);

XMLHttpReq.onreadystatechange = processResponse;

XMLHttpReq.send(null);

}

function processResponse(){

if(XMLHttpReq.readyState == 4){

if(XMLHttpReq.status == 200){

var res = XMLHttpReq.responseXML.getElementsByTagName("res")[0].firstChild.data;

window.alert(res);

document.myform.userid.value="";

document.myform.pwd.value="";

}else{

window.alert("你请求的页面有异常1");

}

}

}

function userCheck(){

var userid = document.myform.userid.value;

var pwd = document.myform.pwd.value;

if(userid == ""){

window.alert("用户名不能为空");

document.myform.pwd.value="";

document.myform.userid.focus();

return false;

}else{

sendRequest("login?userid="+userid);

}

}

function pwdCheck(){

var pwd = document.myform.pwd.value;

var pwd2 = document.myform.pwd2.value;

if(pwd!=pwd2){

window.alert("密码不一致");

document.myform.pwd.value="";

document.myform.pwd2.value="";

document.myform.pwd.focus();

return false;

}

}

/SCRIPT

LINK href="css/css.css" type=text/css rel=stylesheet

/HEAD

body

table width="778" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"

tr

td width="17%"img src="images/logo.jpg" width="124" height="101"/td

td width="558" height="101" background="images/banner.jpg"div align="center"

object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="" width="558" height="101"

param name="movie" value="images/2.swf"

param name="quality" value="high"

embed src="images/2.swf" quality="high" pluginspage="" type="application/x-shockwave-flash" width="558" height="101"/embed

param name="wmode" value="transparent"

/object

/div/td

td width="11%"table width="100%" border="0" cellpadding="0" cellspacing="0"

tr

td height="30" class="style1"div align="center"设为首页/div/td

/tr

tr

td height="30" class="style1"div align="center"收藏本站/div/td

/tr

tr

td height="30" class="style1"div align="center"联系我们/div/td

/tr

/table/td

/tr

/table

form method="post" action="control.jsp?action=register" name="myform"

table width="300" border="0" align="center" bgcolor="#F0F0F0"

tr

td align="center"用户名/td

tdinput name="userid" type="text" size="20" onblur="userCheck()"/td

/tr

tr

td align="center"真实姓名/td

tdinput name="username" type="text" size="20"//td

/tr

tr

td align="center"性别/td

td

input type="radio" name="sex" value="0" checked="checked"男

input type="radio" name="sex" value="1"女

/td

/tr

tr

td align="center"密码/td

tdinput name="pwd" type="password" size="20"//td

/tr

tr

td align="center"密码确认/td

tdinput name="pwd2" type="password" size="20" onblur="pwdCheck()"//td

/tr

tr

td align="center"电子邮箱/td

tdinput name="email" type="text" size="20"//td

/tr

tr

td align="center"学校/td

tdinput name="school" type="text" size="20"//td

/tr

tr

td align="center"电话号码/td

tdinput name="phonenum" type="text" size="20"//td

/tr

tr

td align="center"img border=0 src="image.jsp"/td

tdinput type=text name=in maxlength=4 size="8"/td

/tr

tr

td align="center"input type="submit" value="确定" //td

/tr

/table

/form

/body

/html

ajax获取数据的三种方式

方法一:javascript

方法二:引入jquery

方法三:引入jquery,分get和post方式

此外ajax有四个钩子函数:beforeSend(),success(),error(),complete(),欢迎各方大神指正

如何使用ajax读取数据库中的数据

function test(bid){

$.ajax({

type:"GET",

url:"/test.php?ac=ssbid="+bid+"date=" + new Date(),

success: function(data){

alert(data)

}

});

}

给你发一个简单例子,test.php去获取数据库内容,可以返回不同的数据,如一般的text,也可以是json等多种类型,接收的时候需要做不同的处理

记得在此之前一定先调用JQ库,这是JQ的AJAX方法,个人理解,不专业

ajax获取数据库数据的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于ajax获取数据两种类型、ajax获取数据库数据的信息别忘了在本站进行查找喔。

1、本网站名称:源码村资源网
2、本站永久网址:https://www.yuanmacun.com
3、本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
6、本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。
源码村资源网 » ajax获取数据库数据(ajax获取数据两种类型)
您需要 登录账户 后才能发表评论

发表评论

欢迎 访客 发表评论