Fetching data with Ajax小例子
ajax获取数据示例:
示例1
通过ajax获取txt文件里面的内容示例:
<html>
<head>
<title>Ajax at work</title>
<script type="text/javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID) {
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<H1>Fetching data with Ajax</H1>
<form>
<input type = "button" value = "Display Message" onclick = "getData('data.txt', 'targetDiv')"/>
</form>
<img src="Image1.jpg" onmouseover="getData('sandwiches.txt', 'targetDiv')" onmouseout="getData('data.txt', 'targetDiv')">
<img src="Image2.jpg" onmouseover="getData('pizzas.txt', 'targetDiv1')" onmouseout="getData('data.txt', 'targetDiv1')">
<img src="Image3.jpg" onmouseover="getData('soups.txt', 'targetDiv2')" onmouseout="getData('data.txt', 'targetDiv2')">
<div id="targetDiv"> <p>Welcome to my restaurant!</p> </div>
<div id="targetDiv1"> <p>Welcome to my restaurant!</p> </div>
<div id="targetDiv2"> <p>Welcome to my restaurant!</p> </div>
</body>
</html>
示例2
通过ajax获取XML文件里面的内容示例:
innerHTML.html文件代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Using responseText with innerHTML</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startRequest() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "innerHTML.xml", true);
xmlHttp.send(null);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</head>
<body>
<form action="#" >
<input type="button" value="Search for Today's Activities" onClick="startRequest()" />
</form>
<div id="results"></div>
</body>
</html>
innerHTML.xml文件代码:
<?xml version="1.0" encoding="UTF-8"?>
<table border="1">
<tbody>
<tr>
<th>Activity Name</th>
<th>Location</th>
<th>Time</th>
</tr>
<tr>
<td>Waterskiing</td>
<td>Dock #1</td>
<td>9:00 AM</td>
</tr>
<tr>
<td>Volleyball</td>
<td>East Court</td>
<td>2:00 PM</td>
</tr>
<tr>
<td>Hiking</td>
<td>Trail 3</td>
<td>3:30 PM</td>
</tr>
</tbody>
</table>
运行效果:
示例3
通过ajax解析xml数据
parseXML.html文件里面的代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html >
<head>
<title>Parsing XML Responses with the W3C DOM</title>
<script type="text/javascript">
var xmlHttp;
var requestType = "";
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startRequest(requestedList) {
requestType = requestedList;
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "parseXML.xml", true);
xmlHttp.send(null);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
if(requestType == "north") {
listNorthStates();
}
else if(requestType == "all") {
listAllStates();
}
}
}
}
function listNorthStates() {
var xmlDoc = xmlHttp.responseXML;
var northNode = xmlDoc.getElementsByTagName("north")[0];
var northStates = northNode.getElementsByTagName("state");
outputList("Northern States", northStates);
}
function listAllStates() {
var xmlDoc = xmlHttp.responseXML;
var allStates = xmlDoc.getElementsByTagName("state");
outputList("All States in Document", allStates);
}
function outputList(title, states) {
var out = title;
var currentState = null;
for(var i = 0; i < states.length; i++) {
currentState = states[i];
out = out + "\n- " + currentState.childNodes[0].nodeValue;
}
alert(out);
}
</script>
</head>
<body>
<h1>Process XML Document of U.S. States</h1>
<br/><br/>
<form action="#">
<input type="button" value="View All Listed States" onclick="startRequest('all');"/>
<br/><br/>
<input type="button" value="View All Listed Northern States" onclick="startRequest('north');"/>
</form>
</body>
</html>
parseXML.xml文件里面的代码:
<?xml version="1.0" encoding="UTF-8"?>
<states>
<north>
<state>Minnesota</state>
<state>Iowa</state>
<state>North Dakota</state>
</north>
<south>
<state>Texas</state>
<state>Oklahoma</state>
<state>Louisiana</state>
</south>
<east>
<state>New York</state>
<state>North Carolina</state>
<state>Massachusetts</state>
</east>
<west>
<state>California</state>
<state>Oregon</state>
<state>Nevada</state>
</west>
</states>
运行效果如图所示:
示例4
动态更新显示内容:
dynamicContent.html主要代码如下:
<script type="text/javascript">
createXMLHttpRequest(){
获取XMLHttpRequest代码……
}
function doSearch() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "dynamicContent.xml", true);
xmlHttp.send(null);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
clearPreviousResults();
parseResults();
} } }
function clearPreviousResults() {
var header = document.getElementById("header");
if(header.hasChildNodes()) {
header.removeChild(header.childNodes[0]);
}
var tableBody = document.getElementById("resultsBody");
while(tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]); } }
function parseResults() {
var results = xmlHttp.responseXML;
var property = null; var address = ""; var price = ""; var comments = "";
var min=document.getElementsByName("min");
var max=document.getElementsByName("max");
var minval=min[0].options[min[0].selectedIndex].value; // 选中值
var maxval=max[0].options[max[0].selectedIndex].value; // 选中值
minval=parseFloat(minval); maxval=parseFloat(maxval);
var properties = results.getElementsByTagName("property");
for(var i = 0; i < properties.length; i++) {
property = properties[i];
address = property.getElementsByTagName("address")[0].firstChild.nodeValue;
price = property.getElementsByTagName("price")[0].firstChild.nodeValue;
comments = property.getElementsByTagName("comments")[0].firstChild.nodeValue;
price=parseFloat(price);
if(price>=minval && price<=maxval){
addTableRow(address, price, comments);
};
}
var header = document.createElement("h2");
var headerText = document.createTextNode("Results:");
header.appendChild(headerText);
document.getElementById("header").appendChild(header);
document.getElementById("resultsTable").setAttribute("border", "1"); }
function addTableRow(address, price, comments) {
var row = document.createElement("tr");
var cell = createCellWithText(address);
row.appendChild(cell);
cell = createCellWithText(price);
row.appendChild(cell);
cell = createCellWithText(comments);
row.appendChild(cell);
document.getElementById("resultsBody").appendChild(row);
}
function createCellWithText(text) {
var cell = document.createElement("td");
var textNode = document.createTextNode("$"+text);
cell.appendChild(textNode);
return cell; }
</script>
</head>
<body>
<h1>Search Real Estate Listings</h1>
<form action="#">
Show listings from
<select name="min">
<option value="50000">$50,000</option>
<option value="100000">$100,000</option>
<option value="150000">$150,000</option>
</select >
to
<select name="max">
<option value="100000">$100,000</option>
<option value="150000">$150,000</option>
<option value="200000">$200,000</option>
</select>
<input type="button" value="Search" onclick="doSearch();"/>
</form>
<span id="header"> </span>
<table id="resultsTable" width="75%" border="0"> <tbody id="resultsBody"> </tbody> </table>
</body>
</html>
dynamicContent.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>
<address>812 Gwyn Ave</address>
<price>90000</price>
<comments>Quiet, serene neighborhood</comments>
</property>
<property>
<address>812 Gwyn Ave</address>
<price>100000</price>
<comments>Quiet, serene neighborhood</comments>
</property>
<property>
<address>3308 James Ave S</address>
<price>110000</price>
<comments>Close to schools, shopping, entertainment</comments>
</property>
<property>
<address>98320 County Rd 113</address>
<price>155000</price>
<comments>Small acreage outside of town</comments>
</property>
</properties>
运行效果:
顺便附上GET和POST方法的相关代码:
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
获取XMLHttpRequest代码……
}
function createQueryString() {
var firstName = document.getElementById("firstName").value;
var middleName = document.getElementById("middleName").value;
var birthday = document.getElementById("birthday").value;
var queryString = "firstName=" + firstName + "&middleName=" + middleName + "&birthday=" + birthday;
return queryString;
}
function doRequestUsingGET() {
createXMLHttpRequest();
var queryString = "data.txt?";
queryString = queryString + createQueryString()
+ "&timeStamp=" + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", queryString, true);
xmlHttp.send(null);
}
function doRequestUsingPOST() {
createXMLHttpRequest();
var url = "data.txt?timeStamp=" + new Date().getTime();
var queryString = createQueryString();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
/* 含义是表示客户端提交给服务器文本内容的编码方式 是URL编码,即除了标准字符外,每字节以双字节16进制前加个“%”表示,
setRequestHeader方法只是XMLHTTP为添加或修改HTTP头提供的一个接口方法而已, 至于里面的值则是HTTP协议的含义. */
xmlHttp.send(queryString);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText); }
post xml文件
function createXML() {
var xml = "<pets>";
var options = document.getElementById("petTypes").childNodes;
var option = null;
for(var i = 0; i < options.length; i++) {
option = options[i];
if(option.selected) {
xml = xml + "<type>" + option.value + "</type>";
}
}
xml = xml + "</pets>"; return xml;
}
function sendPetTypes() {
createXMLHttpRequest();
var xml = createXML();
var url = "data.txt?timeStamp=" + new Date().getTime();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(xml);
}
</script>
发送json数据到后台:
<script type="text/javascript" src="json.js"></script>
function doJSON() {
var car = getCarObject();
//Use the JSON JavaScript library to stringify the Car object
var carAsJSON = JSON.stringify(car);
alert("Car object as JSON:\n " + carAsJSON);
var url = "data.txt?timeStamp=" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(carAsJSON);
}
function getCarObject() {
此处可以获取表单数据,代替下面的参数……
return new Car("Dodge", "Coronet R/T", 1968, "yellow");
}
function Car(make, model, year, color)
{ this.make = make; this.model = model; this.year = year; this.color = color; }
Fetching data with Ajax小例子的更多相关文章
- php+jquery+ajax+json简单小例子
直接贴代码: <html> <title>php+jquery+ajax+json简单小例子</title> <?php header("Conte ...
- Ajax入门小例子
大牛文章:http://www.cnblogs.com/guduoduo/p/3681296.html ---Ajax基础学习 http:/ ...
- 【zTree】 zTree使用的 小例子
使用zTree树不是第一次了 但是 还是翻阅着之前做的 对照着 使用起来比较方便 这里就把小例子列出来 总结一下使用步骤 这样方便下次使用起来方便一点 使用zTree树的步骤: 1.首先 在 ...
- html5 file upload and form data by ajax
html5 file upload and form data by ajax 最近接了一个小活,在短时间内实现一个活动报名页面,其中遇到了文件上传. 我预期的效果是一次ajax post请求,然后在 ...
- c# BackGroundWorker 多线程操作的小例子
在我们的程序中,经常会有一些耗时较长的运算,为了保证用户体验,不引起界面不响应,我们一般会采用多线程操作,让耗时操作在后台完成,完成后再进行处理或给出提示,在运行中,也会时时去刷新界面上的进度条等显示 ...
- 我的Android进阶之旅------>Android拍照小例子
今天简单的学习了一下android拍照的简单实现. 当然该程序是个小例子,非常简单,没有什么复杂的操作,但是可以学习到Android 拍照API流程. 1.在布局文件中添加一个 surfaceView ...
- lucene.net 3.0.3、结合盘古分词进行搜索的小例子(转)
lucene.net 3.0.3.结合盘古分词进行搜索的小例子(分页功能) 添加:2013-12-25 更新:2013-12-26 新增分页功能. 更新:2013-12-27 新增按分类查询功能, ...
- 2、Lucene 最简单的使用(小例子)
在了解了Lucene以后,我打算亲手来做一个Lucene的小例子,这个例子只是Lucene最简单的应用:使用Lucene实现标准的英文搜索: 1.下载Lucene 下载Lucene,到Lucene的官 ...
- C# 关于委托的小例子
本例子是一个关于委托的小例子[猫叫,狗跳,人喊]. 委托是C#开发中一个非常重要的概念,理解起来也和常规的方法不同,但一旦理解清楚,就可以信手拈来,随处可用. 委托是对方法的抽象.它存储的就是一系列具 ...
随机推荐
- C++中输出流的刷新问题和 endl和 \n的区别
<C++ Primer>第5版 P6中提到endl具有换行和刷新输出流两个作用,那么没有 endl是否还会将输出流中的内容输出到设备中,再刷新输出流呢? cout << &qu ...
- python内置函数 divmod()
先来看一下builtins.py中的代码: def divmod(x, y): # known case of builtins.divmod """ Return th ...
- C#数组随机生成四个随机数
int[] face = new int[4]; Random ra = new Random(); for (int i = 0; i < face.Length; i++) { int co ...
- 201621123040《Java程序设计》第六周学习总结
1.本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图或相关笔记,对面向对象思想进行一个总结 2.书面作业 2.1clone方法 2.1.1在te ...
- GPUImage滤镜效果翻译
#import"GPUImageBrightnessFilter.h"//亮度 #import"GPUImageExposureFilter.h"//曝光 #i ...
- Fluent Interface(流式接口)
我最初接触这个概念是读自<<模式-工程化实现及扩展>>,另外有Martin fowler大师 所写http://martinfowler.com/bliki/FluentInt ...
- js判断操作系统windows,ios,android(笔记)
使用JS判断用户使用的系统是利用浏览器的userAgent. navigator.userAgent:userAgent 获取了浏览器用于 HTTP 请求的用户代理头的值. navigator.pla ...
- Spring Cache扩展:注解失效时间+主动刷新缓存(二)
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
- 第一章 jQuery基础
第一章jQuery基础 一.jQuert简介 1.什么是jQuery jQuery是javaScript的程序库之一,它是javaScript对象和实用函数的封装. jQuery是继Prototype ...
- Nagios监控的部署与配置
[安装Nagios] yum install -y httpd httpd-devel httpd-tools mysql mysql-devel mysql-server php php-devel ...