遵义网站设计制作网站,天津做网站选津坤科技,做网站对比报告,保定网站建设Web API 是开发人员的梦想。
它可以扩展浏览器的功能它可以极大简化复杂的功能它可以为复杂的代码提供简单的语法
什么是 Web API#xff1f;
API 指的是应用程序编程接口#xff08;Application Programming Interface#xff09;。
Web API 是 Web 的应用程序编程接口…Web API 是开发人员的梦想。
它可以扩展浏览器的功能它可以极大简化复杂的功能它可以为复杂的代码提供简单的语法
什么是 Web API
API 指的是应用程序编程接口Application Programming Interface。
Web API 是 Web 的应用程序编程接口。
浏览器 API 可以扩展 Web 浏览器的功能。
服务器 API 可以扩展 Web 服务器的功能。
浏览器 API
所有浏览器都有一组内置的 Web API 来支持复杂的操作并帮助访问数据。
例如Geolocation API 可以返回浏览器所在位置的坐标。
JavaScript 验证 API
约束验证 DOM 方法
属性描述checkValidity()如果 input 元素包含有效数据则返回 true。setCustomValidity()设置 input 元素的 validationMessage 属性。
!DOCTYPE html
html
bodyh1JavaScript 验证/h1p请输入一个数字然后点击 OK/pinput idid1 typenumber min100 max300 required
button onclickmyFunction()OK/buttonp如果数字小于 100 或大于 300将显示错误消息。/pp iddemo/pscript
function myFunction() {const inpObj document.getElementById(id1);if (!inpObj.checkValidity()) {document.getElementById(demo).innerHTML inpObj.validationMessage;} else {document.getElementById(demo).innerHTML Input OK;}
}
/script/body
/html
约束验证 DOM 属性
属性描述validity包含与输入元素有效性相关的布尔属性。validationMessage包含当有效性为 false 时浏览器将显示的消息。willValidate指示是否将验证 input 元素。
有效性属性
input 元素的有效性属性包含许多与数据有效性相关的属性
属性描述customError如果设置了自定义有效性消息则设置为 true。patternMismatch如果元素的值与其 pattern 属性不匹配则设置为 true。rangeOverflow如果元素的值大于其 max 属性则设置为 true。rangeUnderflow如果元素的值小于其 min 属性则设置为 true。stepMismatch如果元素的值对其 step 属性无效则设置为 true。tooLong如果元素的值超过其 maxLength 属性则设置为 true。typeMismatch如果元素的值对其 type 属性无效则设置为 true。valueMissing如果元素具有 required 属性没有值则设置为 true。valid如果元素的值有效则设置为 true。
Web History API
Web History API 提供了访问 windows.history 对象的简单方法。
window.history 对象包含用户访问过的 URL网站。
所有浏览器都支持 Web History API
History back() 方法
back() 方法加载 windows.history 列表中的前一个 URL。
这与单击浏览器中的“后退箭头”相同。
button onclickmyFunction()后退/buttonscript
function myFunction() {window.history.back();
}
/script
History go() 方法
go() 方法从历史列表中加载一个特定的 URL
button onclickmyFunction()后退两页/buttonscript
function myFunction() {window.history.go(-2);
}
/script
History 对象属性
属性描述length返回历史列表中的 URL 数量。
History 对象方法
方法描述back()加载历史列表中的上一个 URL。forward()加载历史列表中的下一个 URL。go()从历史列表中加载特定的 URL。
Web Worker API
Web Worker 是在后台运行的 JavaScript不会影响页面的性能。
什么是 Web Worker
在 HTML 页面中执行脚本时页面在脚本完成之前是无响应的。
Web Worker 是在后台运行的 JavaScript独立于其他脚本不会影响页面的性能。你可以继续做任何你想做的事情点击、选取内容等同时 web worker 在后台运行。
检查 Web Worker 浏览器
在创建 web worker 之前请检查用户的浏览器是否支持它
if (typeof(Worker) ! undefined) {// Yes! Web worker support!// Some code.....
} else {// Sorry! No Web Worker support..
}
创建 Web Worker 文件
现在让我们在外部 JavaScript 中创建我们的 Web Worker。
在这里我们创建了一个重要的脚本。该脚本存储在 demo_workers.js 文件中
let i 0;function timedCount() {i ;postMessage(i);setTimeout(timedCount(),500);
}timedCount();
创建 Web Worker 对象
现在我们有了 web worker 文件我们需要从 HTML 页面调用它。
以下代码行检查 worker 是否已存在如果不存在它会创建一个新的 web worker 对象并运行 demo_workers.js 中的代码
if (typeof(w) undefined) {w new Worker(demo_workers.js);
}然后我们可以发送和接收来自 web worker 的消息。
向 web worker 添加一个 onmessage 事件侦听器。
w.onmessage function(event){document.getElementById(result).innerHTML event.data;
};当 Web Worker 发布消息时将执行事件侦听器中的代码。来自 Web Worker 的数据存储在 event.data 中。
终止 Web Worker
当 web worker 对象被创建时它会继续监听消息即使在外部脚本完成之后直到它被终止。
如需终止 web worker并释放浏览器/计算机资源请使用 terminate() 方法
w.terminate();
重用 Web Worker
如果将 worker 变量设置为 undefined则在它终止后您可以重用以下代码
w undefined;
!DOCTYPE html
html
bodyh1JavaScript Web Workers API/h1
pCount numbers: output idresult/output/p
button onclickstartWorker()开始 Worker/button
button onclickstopWorker()停止 Worker/buttonscript
let w;function startWorker() {if(typeof(w) undefined) {w new Worker(demo_workers.js);}w.onmessage function(event) {document.getElementById(result).innerHTML event.data;};
}function stopWorker() { w.terminate();w undefined;
}
/script/body
/htmlWeb Worker 和 DOM
由于 Web Worker 位于外部文件中因此他们无法访问以下 JavaScript 对象
window 对象document 对象parent 对象
JavaScript Fetch API
Fetch API 接口允许 Web 浏览器向 Web 服务器发出 HTTP 请求。
不再需要 XMLHttpRequest。
Fetch API 实例
下面的例子获取文件并显示内容
!DOCTYPE html
html
body
p iddemo获取文件以更改此文本。/p
scriptlet file /demo/js/fetch_info.txtfetch (file)
.then(x x.text())
.then(y document.getElementById(demo).innerHTML y);/script
/body
/html由于 Fetch 基于 async 和 await因此上面的例子这么写可能更容易理解
Web Geolocation API
定位用户的位置
HTML Geolocation API 用于获取用户的地理位置。
由于这可能会损害隐私除非用户批准否则位置不可用。
!DOCTYPE html
html
bodyh3如何访问 ABBR 元素的演示/h3pThe abbr idmyAbbr titleWorld Health OrganizationWHO/abbr was founded in 1948./pp单击按钮可获取“WHO”的缩写。/pbutton onclickmyFunction()试一试/buttonp iddemo/pscript
function myFunction() {var x document.getElementById(myAbbr).title;document.getElementById(demo).innerHTML x;
}
/script/body
/html使用 Geolocation API
getCurrentPosition() 方法用于返回用户的位置。
下面的例子返回用户位置的纬度和经度
!DOCTYPE html
html
bodyh1JavaScript Geolocation API/h1p请单击按钮以获取您的坐标。/pbutton onclickgetLocation()试一试/buttonp iddemo/pscript
const x document.getElementById(demo);function getLocation() {if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(showPosition);} else { x.innerHTML Geolocation is not supported by this browser.;}
}function showPosition(position) {x.innerHTML Latitude: position.coords.latitude brLongitude: position.coords.longitude;
}
/script/body
/html例子解释
检查是否支持 Geolocation如果支持请运行 getCurrentPosition() 方法。如果没有则向用户显示一条消息如果 getCurrentPosition() 方法成功则返回一个 coordinates 对象给参数 (showPosition) 中规定的函数showPosition() 函数输出纬度和经度
!DOCTYPE html
html
bodyh1JavaScript Geolocation API/h1p单击按钮以获取您的坐标。/pbutton onclickgetLocation()试一试/buttonp iddemo/pscript
const x document.getElementById(demo);function getLocation() {if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(showPosition, showError);} else { x.innerHTML Geolocation is not supported by this browser.;}
}function showPosition(position) {x.innerHTML Latitude: position.coords.latitude brLongitude: position.coords.longitude;
}function showError(error) {switch(error.code) {case error.PERMISSION_DENIED:x.innerHTML User denied the request for Geolocation.break;case error.POSITION_UNAVAILABLE:x.innerHTML Location information is unavailable.break;case error.TIMEOUT:x.innerHTML The request to get user location timed out.break;case error.UNKNOWN_ERROR:x.innerHTML An unknown error occurred.break;}
}
/script/body
/html在地图中显示结果
如需在地图中显示结果您需要访问地图服务例如 Google 地图。
在下面的例子中返回的纬度和经度用于在 Google 地图中显示位置使用静态图像
function showPosition(position) {let latlon position.coords.latitude , position.coords.longitude;let img_url https://maps.googleapis.com/maps/api/staticmap?centerlatlonzoom14size400x300sensorfalsekeyYOUR_KEY;document.getElementById(mapholder).innerHTML img srcimg_url;
}
getCurrentPosition() 方法 - 返回数据
getCurrentPosition() 方法在成功时返回一个对象。会始终返回纬度、经度和精度属性。如果可用则返回其他属性
属性返回coords.latitude以十进制数表示的纬度始终返回。coords.longitude以十进制数表示的经度始终返回。coords.accuracy位置精度始终返回。coords.altitude平均海平面以上的高度以米计如果可用则返回。coords.altitudeAccuracy位置的高度精度如果可用则返回。coords.heading从北顺时针方向的航向如果可用则返回。coords.speed以米/秒计的速度如果可用则返回。timestamp响应的日期/时间如果可用则返回。
Geolocation 对象 - 其他有趣的方法
Geolocation 对象还有其他有趣的方法
watchPosition() - 返回用户的当前位置并随着用户移动如汽车中的 GPS继续返回更新的位置。clearWatch() - 停止 watchPosition () 方法。
下面的例子展示了 watchPosition() 方法。你需要准确的 GPS 设备来测试比如智能手机
!DOCTYPE html
html
bodyh1JavaScript Geolocation API/h1p单击按钮以获取您的坐标。/pbutton onclickgetLocation()试一试/buttonp iddemo/pscript
const x document.getElementById(demo);function getLocation() {if (navigator.geolocation) {navigator.geolocation.watchPosition(showPosition);} else { x.innerHTML Geolocation is not supported by this browser.;}
}function showPosition(position) {x.innerHTMLLatitude: position.coords.latitude brLongitude: position.coords.longitude;
}
/script/body
/html
AJAX 简介
什么是 AJAX
AJAX Asynchronous JavaScript And XML.
AJAX 并非编程语言。
AJAX 仅仅组合了
浏览器内建的 XMLHttpRequest 对象从 web 服务器请求数据JavaScript 和 HTML DOM显示或使用数据
Ajax 是一个令人误导的名称。Ajax 应用程序可能使用 XML 来传输数据但将数据作为纯文本或 JSON 文本传输也同样常见。
Ajax 允许通过与场景后面的 Web 服务器交换数据来异步更新网页。这意味着可以更新网页的部分而不需要重新加载整个页面。 AJAX 是开发者的梦想因为您能够
不刷新页面更新网页在页面加载后从服务器请求数据在页面加载后从服务器接收数据在后台向服务器发送数据
AJAX 实例
单击下面的按钮让 Ajax 改变这段文本
!DOCTYPE html
html
bodydiv iddemo
h1XMLHttpRequest 对象/h1
button typebutton onclickloadDoc()修改内容/button
/divscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, /demo/js/ajax_info.txt, true);xhttp.send();
}
/script/body
/html网页中发生一个事件页面加载、按钮点击由 JavaScript 创建 XMLHttpRequest 对象XMLHttpRequest 对象向 web 服务器发送请求服务器处理该请求服务器将响应发送回网页由 JavaScript 读取响应由 JavaScript 执行正确的动作比如更新页面
AJAX - XMLHttpRequest 对象
XMLHttpRequest 对象是 AJAX 的基石。
创建 XMLHttpRequest 对象定义回调函数打开 XMLHttpRequest 对象向服务器发送请求 XMLHttpRequest 对象
所有现代浏览器都支持 XMLHttpRequest 对象。
XMLHttpRequest 对象可用于在后台与 Web 服务器交换数据。这意味着可以更新网页的部分内容而无需重新加载整个页面。
创建 XMLHttpRequest 对象
所有现代浏览器Chrome、Firefox、IE、Edge、Safari、Opera都有内置的 XMLHttpRequest 对象。
创建 XMLHttpRequest 对象的语法 variable new XMLHttpRequest(); 定义回调函数
回调函数是作为参数传递给另一个函数的函数。
在这种情况下回调函数应包含响应准备就绪时要执行的代码。 xhttp.onload function() {// 当响应准备就绪时要做什么
}发送请求
如需向服务器发送请求您可以使用 XMLHttpRequest 对象的 open() 和 send() 方法 xhttp.open(GET, ajax_info.txt);
xhttp.send(); // 创建 XMLHttpRequest 对象
const xhttp new XMLHttpRequest();// 定义回调函数
xhttp.onload function() {// 您可以在这里使用数据
}// 发送请求
xhttp.open(GET, ajax_info.txt);
xhttp.send();
跨域访问Access Across Domains
出于安全原因现代浏览器不允许跨域访问。
这意味着网页和它尝试加载的 XML 文件必须位于同一台服务器上。
W3School 上的例子都打开位于 W3School 域中的 XML 文件。
如果您想在自己的网页之一上使用上面的例子您加载的 XML 文件必须位于您自己的服务器上
XMLHttpRequest 对象方法
方法描述new XMLHttpRequest()创建新的 XMLHttpRequest 对象。abort()取消当前请求。getAllResponseHeaders()返回头部信息。getResponseHeader()返回特定的头部信息。open(method, url, async, user, psw) 规定请求。 method请求类型 GET 或 POSTurl文件位置asynctrue异步或 false同步user可选的用户名psw可选的密码send()向服务器发送请求用于 GET 请求。send(string)向服务器发送请求用于 POST 请求。setRequestHeader()将标签/值对添加到要发送的标头。 XMLHttpRequest 对象属性
属性描述onload定义接收到加载请求时要调用的函数。onreadystatechange定义当 readyState 属性发生变化时调用的函数。readyState 保存 XMLHttpRequest 的状态。 0请求未初始化1服务器连接已建立2请求已收到3正在处理请求4请求已完成且响应已就绪responseText以字符串形式返回响应数据。responseXML以 XML 数据返回响应数据。status 返回请求的状态号 200: OK403: Forbidden404: Not Found如需完整列表请访问 Http 消息参考手册 statusText返回状态文本比如 OK 或 Not Found 多个回调函数
如果网站中有多个 AJAX 任务则应创建一个执行 XMLHttpRequest 对象的函数并为每个 AJAX 任务创建一个回调函数。
函数调用应包含 URL 以及响应准备就绪时要调用的函数。
loadDoc(url-1, myFunction1);loadDoc(url-2, myFunction2);function loadDoc(url, cFunction) {const xhttp new XMLHttpRequest();xhttp.onload function() {cFunction(this);}xhttp.open(GET, url);xhttp.send();
}function myFunction1(xhttp) {// 这里是动作
}
function myFunction2(xhttp) {// 这里是动作
}
onreadystatechange 属性
readyState 属性保存 XMLHttpRequest 的状态。
onreadystatechange 属性定义了一个回调函数当 readyState 改变时执行该函数。
status 属性和 statusText 属性保存 XMLHttpRequest 对象的状态。 属性描述onreadystatechange定义当 readyState 属性改变时调用的函数。readyState 保存 XMLHttpRequest 的状态。 0请求未初始化1服务器连接已建立2请求已收到3正在处理请求4请求已完成且响应已就绪status 返回请求的状态号 200: OK403: Forbidden404: Not Found如需完整列表请访问 Http 消息参考手册 statusText返回状态文本比如 OK 或 Not Found。
function loadDoc() {const xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, ajax_info.txt);xhttp.send();
}
AJAX - XMLHttpRequest
XMLHttpRequest 对象用于同服务器交换数据。
向服务器发送请求
如需向服务器发送请求我们使用 XMLHttpRequest 对象的 open() 和 send() 方法 xhttp.open(GET, ajax_info.txt, true);
xhttp.send(); 方法描述open(method, url, async) 规定请求的类型 method请求的类型GET 还是 POSTurl服务器文件位置asynctrue异步或 false同步send()向服务器发送请求用于 GETsend(string)向服务器发送请求用于 POST
GET 还是 POST
GET 比 POST 更简单更快可用于大多数情况下。
不过请在以下情况始终使用 POST
缓存文件不是选项更新服务器上的文件或数据库向服务器发送大量数据POST 无大小限制发送用户输入可包含未知字符POST 比 GET 更强大更安全\
GET 请求
一条简单的 GET 请求
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1button typebutton onclickloadDoc()请求数据/buttonp iddemo/pscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, /demo/demo_get.asp, true);xhttp.send();
}
/script/body
/html在上面的例子中您可能会获得一个缓存的结果。为了避免此情况请向 URL 添加一个唯一的 ID
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1button typebutton onclickloadDoc()请求数据/buttonp单击该按钮几次以查看时间是否已更改或文件是否已缓存。/pp iddemo/pscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechangefunction() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, /demo/demo_get.asp?t Math.random(), true);xhttp.send();
}
/script/body
/html如果您需要用 GET 方法来发送信息请向 URL 添加这些信息
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1button typebutton onclickloadDoc()请求数据/buttonp iddemo/pscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, /demo/demo_get2.asp?fnameBilllnameGates, true);xhttp.send();
}
/script/body
/htmlPOST 请求
一条简单的 POST 请求
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1button typebutton onclickloadDoc()请求数据/buttonp iddemo/pscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(POST, /demo/demo_post.asp, true);xhttp.send();
}
/script/body
/html如需像 HTML 表单那样 POST 数据请通过 setRequestHeader() 添加一个 HTTP 头部。请在 send() 方法中规定您需要发送的数据
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1button typebutton onclickloadDoc()请求数据/buttonp iddemo/pscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(POST, /demo/demo_post2.asp, true);xhttp.setRequestHeader(Content-type, application/x-www-form-urlencoded);xhttp.send(fnameBilllnameGates);
}
/script/body
/html方法描述setRequestHeader(header, value) 向请求添加 HTTP 头部 header规定头部名称value规定头部值
url - 服务器上的文件
open() 方法的 url 参数是服务器上文件的地址
xhttp.open(GET, ajax_test.asp, true);
该文件可以是任何类型的文件如 .txt 和 .xml或服务器脚本文件如 .asp 和 .php它们可以在发送回响应之前在服务器执行操作。
异步 - true 还是 false
如需异步发送请求open() 方法的 async 参数必须设置为 true
xhttp.open(GET, ajax_test.asp, true);
onreadystatechange 属性
通过 XMLHttpRequest 对象您可以定义当请求接收到应答时所执行的函数。
这个函数是在 XMLHttpResponse 对象的 onreadystatechange 属性中定义的
!DOCTYPE html
html
bodydiv iddemo
h1XMLHttpRequest 对象/h1
button typebutton onclickloadDoc()更改内容/button
/divscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, /demo/js/ajax_info.txt, true);xhttp.send();
}
/script/body
/html
同步请求
如需执行同步的请求请把 open() 方法中的第三个参数设置为 false
xhttp.open(GET, ajax_info.txt, false);
有时 async false 用于快速测试。你也会在更老的 JavaScript 代码中看到同步请求。
由于代码将等待服务器完成所以不需要 onreadystatechange 函数
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1p iddemo让 AJAX 更改这段文本。/pbutton typebutton onclickloadDoc()更改内容/buttonscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.open(GET, /demo/js/ajax_info.txt, false);xhttp.send();document.getElementById(demo).innerHTML xhttp.responseText;
}
/script/body
/html我们不推荐同步的 XMLHttpRequest (async false)因为 JavaScript 将停止执行直到服务器响应就绪。如果服务器繁忙或缓慢应用程序将挂起或停止。
同步 XMLHttpRequest 正在从 Web 标准中移除但是这个过程可能需要很多年。
现代开发工具被鼓励对使用同步请求做出警告并且当这种情况发生时可能会抛出 InvalidAccessError 异常
AJAX - 服务器响应
onreadystatechange 属性
readyState 属性存留 XMLHttpRequest 的状态。
onreadystatechange 属性定义当 readyState 发生变化时执行的函数。
status 属性和 statusText 属性存有 XMLHttpRequest 对象的状态。
属性描述onreadystatechange定义了当 readyState 属性发生改变时所调用的函数。readyState 保存了 XMLHttpRequest 的状态。 0: 请求未初始化1: 服务器连接已建立2: 请求已接收3: 正在处理请求4: 请求已完成且响应已就绪status 200: OK403: Forbidden404: Page not found如需完整列表请访问 Http 消息参考手册 statusText返回状态文本例如 OK 或 Not Found
每当 readyState 发生变化时就会调用 onreadystatechange 函数。
!DOCTYPE html
html
bodydiv iddemo
h1XMLHttpRequest 对象/h1
button typebutton onclickloadDoc()更改内容/button
/divscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, /demo/js/ajax_info.txt, true);xhttp.send();
}
/script/body
/html使用回调函数
回调函数是一种作为参数被传递到另一个函数的函数。
如果您的网站中有多个 AJAX 任务那么您应该创建一个执行 XMLHttpRequest 对象的函数以及一个供每个 AJAX 任务的回调函数。
该函数应当包含 URL 以及当响应就绪时调用的函数。
实例
!DOCTYPE html
html
bodydiv iddemoh1XMLHttpRequest 对象/h1button typebutton onclickloadDoc(/demo/js/ajax_info.txt, myFunction)更改内容
/button
/divscript
function loadDoc(url, cFunction) {var xhttp;xhttpnew XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {cFunction(this);}};xhttp.open(GET, url, true);xhttp.send();
}
function myFunction(xhttp) {document.getElementById(demo).innerHTML xhttp.responseText;
}
/script
/body
/html服务器响应属性
属性描述responseText获取字符串形式的响应数据responseXML获取 XML 数据形式的响应数据
服务器响应方法
方法描述getResponseHeader()从服务器返回特定的头部信息getAllResponseHeaders()从服务器返回所有头部信息
esponseText 属性
responseText 属性以 JavaScript 字符串的形式返回服务器响应因此您可以这样使用它
!DOCTYPE html
html
bodydiv iddemo
h1XMLHttpRequest 对象/h1
button typebutton onclickloadDoc()更改内容/button
/divscript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.responseText;}};xhttp.open(GET, /demo/js/ajax_info.txt, true);xhttp.send();
}
/script/body
/htmlresponseXML 属性
XML HttpRequest 对象有一个內建的 XML 解析器。
ResponseXML 属性以 XML DOM 对象返回服务器响应。
使用此属性您可以把响应解析为 XML DOM 对象
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1p iddemo/pscript
var xhttp, xmlDoc, txt, x, i;
xhttp new XMLHttpRequest();
xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {xmlDoc this.responseXML;txt ;x xmlDoc.getElementsByTagName(ARTIST);for (i 0; i x.length; i) {txt txt x[i].childNodes[0].nodeValue br;}document.getElementById(demo).innerHTML txt;}
};
xhttp.open(GET, /demo/music_list.xml, true);
xhttp.send();
/script/body
/html
getAllResponseHeaders() 方法
getAllResponseHeaders() 方法返回所有来自服务器响应的头部信息。
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1pgetAllResponseHeaders() 函数返回资源的所有头信息如长度服务器类型内容类型最后修改等/pp iddemo/pscript
var xhttp new XMLHttpRequest();
xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.getAllResponseHeaders();}
};
xhttp.open(GET, /demo/js/ajax_info.txt, true);
xhttp.send();
/script/body
/html
getResponseHeader() 方法
getResponseHeader() 方法返回来自服务器响应的特定头部信息。
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1pgetResponseHeader() 函数返回资源的特定头信息如长度服务器类型内容类型最后修改等/pp最后修改时间span iddemo/span/pscript
var xhttpnew XMLHttpRequest();
xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(demo).innerHTML this.getResponseHeader(Last-Modified);}
};
xhttp.open(GET, /demo/js/ajax_info.txt, true);
xhttp.send();
/script/body
/htmlAJAX XML 实例
!DOCTYPE html
html
style
table,th,td {border : 1px solid black;border-collapse: collapse;
}
th,td {padding: 5px;
}
/style
bodyh1XMLHttpRequest 对象/h1button typebutton onclickloadDoc()获取我的音乐列表/button
brbr
table iddemo/tablescript
function loadDoc() {var xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {myFunction(this);}};xhttp.open(GET, /demo/music_list.xml, true);xhttp.send();
}
function myFunction(xml) {var i;var xmlDoc xml.responseXML;var tabletrth艺术家/thth曲目/th/tr;var x xmlDoc.getElementsByTagName(TRACK);for (i 0; i x.length; i) { table trtd x[i].getElementsByTagName(ARTIST)[0].childNodes[0].nodeValue /tdtd x[i].getElementsByTagName(TITLE)[0].childNodes[0].nodeValue /td/tr;}document.getElementById(demo).innerHTML table;
}
/script/body
/html
AJAX ASP 实例
下面的例子演示当用户在输入字段中键入字符时网页如何与 web 服务器进行通信
!DOCTYPE html
html
bodyh1XMLHttpRequest 对象/h1h2请在下面的输入字段中键入字母 A-Z/h2p搜索建议span idtxtHint/span/p p姓名input typetext idtxt1 onkeyupshowHint(this.value)/pscript
function showHint(str) {var xhttp;if (str.length 0) { document.getElementById(txtHint).innerHTML ;return;}xhttp new XMLHttpRequest();xhttp.onreadystatechange function() {if (this.readyState 4 this.status 200) {document.getElementById(txtHint).innerHTML this.responseText;}};xhttp.open(GET, /demo/gethint.asp?qstr, true);xhttp.send();
}
/script/body
/html
代码解释
首先检查输入字段是否为空str.length 0如果是清空 txtHint 占位符的内容并退出函数。
不过如果输入字段不为空则进行如下
创建 XMLHttpRequest 对象创建当服务器响应就绪时执行的函数发送请求到服务器上的 ASP 文件gethint.asp请注意添加到 gethint.asp 的 q 参数str 变量保存了输入字段的内容
AJAX Database 实例
AJAX 可用于同数据库进行交互式通信。
AJAX Database 实例
下面的例子演示网页如何通过 AJAX 从数据库中读取信息