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#开发中一个非常重要的概念,理解起来也和常规的方法不同,但一旦理解清楚,就可以信手拈来,随处可用. 委托是对方法的抽象.它存储的就是一系列具 ...
随机推荐
- JavaScript(第六天)【函数】
函数是定义一次但却可以调用或执行任意多次的一段JS代码.函数有时会有参数,即函数被调用时指定了值的局部变量.函数常常使用这些参数来计算一个返回值,这个值也成为函数调用表达式的值. 一.函数声明 函 ...
- python第三方库requests详解
Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTT ...
- 使用XIB实现嵌套自定义视图
在进行iOS开发的过程中,对于一些复杂的界面,我们可以通过Interface Builder这个Xcode集成的可视化界面编辑工具在完成,这回节省大部分时间以及代码量.它的使用方法这里不做介绍了,这次 ...
- WingIDE5.*注册破解方法
WingIDE是Python程序语言设计的集成开发环境,具有语法标签高亮显示,命令自动完成和函数跳转列表等非常强大的功能.本文主要介绍WingIDE 5安装及注册破解方法. 1. WingIDE 5下 ...
- c# 字符串的内存分配和驻留池( 转 )
刚开始学习C#的时候,就听说CLR对于String类有一种特别的内存管理机制:有时候,明明声明了两个String类的对象,但是他们偏偏却指向同一个实例.如下: string s1 = "he ...
- Docker学习实践 - Docker安装MySql数据库
Docker安装MySQL数据库 1.Ubuntu安装MySQL安装 (1)安装编译源码需要的包 sudo apt-get install make cmake gcc g++ bison libnc ...
- OAuth2.0学习(1-6)授权方式3-密码模式(Resource Owner Password Credentials Grant)
授权方式3-密码模式(Resource Owner Password Credentials Grant) 密码模式(Resource Owner Password Credentials Grant ...
- mysql批量插入语句执行失败的话,是部分失败还是全部失败
项目开发中,正好遇到这个问题. 将一批从外部第三方接口获取到的数据存储到本地mysql数据库,假设接口返回的数据类型为A,经过A到B的转换规则转换后, 要插入数据库的数据类型为B.那么在A获取到100 ...
- 关于HTML
我的PHP学习之旅 学习PHP已经有一段时间了,今天才想好好的总结一下这一路走来的点点滴滴,也想把我的学习方法及经验分享给大家,希望能对你有所帮助. 首先学习的是PHP前端部分,这里需要学习的知识有H ...
- global关键字修改全局变量
#我们知道全局变量在函数外部,强烈建议不要在函数内部修改全局变量,正常情况下,在函数内部改变全局变量并不影响全局变量的值,举例如下 count = 5 >>> def myfun() ...