Ajax 核心框架函数及例子
网络编程 2021-07-05 10:37www.168986.cn编程入门
最近学习js,肯定会学到ajax中的东西,所以,看到比较好的ajax函数,免不得要贴出来,供大家参考。这个函数摘录自john resig的书中。
核心ajax(options)函数中,包含了建立xmlhttprequest,提取数据,判断是否回复成功等,基本满足了日常需求。
// A generic function for performming AJAX requests
// It takes one argument, which is an object that contains a set of options
// All of which are outline in the ments, below
function ajax( options ) {
// Load the options object with defaults, if no
// values were provided by the user
options = {
// The type of HTTP Request
type: options.type || "POST",
// The URL the request will be made to
url: options.url || "",
// How long to wait before considering the request to be a timeout
timeout: options.timeout || 5000,
// Functions to call when the request fails, sueeds,
// or pletes (either fail or sueed)
onComplete: options.onComplete || function(){},
onError: options.onError || function(){},
onSuess: options.onSuess || function(){},
// The data type that'll be returned from the server
// the default is simply to determine what data was returned from the
// and act aordingly.
data: options.data || ""
};
// Create the request object
var xml = new XMLHttpRequest();
// Open the asynchronous POST request
//xml.open("GET", "/some/url.cgi", true);
xml.open("GET",options.url, true);
// We're going to wait for a request for 5 seconds, before giving up
var timeoutLength = 5000;
// Keep track of when the request has been suesfully pleted
var requestDone = false;
// Initalize a callback which will fire 5 seconds from now, cancelling
// the request (if it has not already ourred).
setTimeout(function(){
requestDone = true;
}, timeoutLength);
// Watch for when the state of the document gets updated
xml.onreadystatechange = function(){
// Wait until the data is fully loaded,
// and make sure that the request hasn't already timed out
if ( xml.readyState == 4 && !requestDone ) {
// Check to see if the request was suessful
if ( httpSuess( xml ) ) {
// Execute the suess callback with the data returned from the server
options.onSuess( httpData( xml, options.type ) );
// Otherwise, an error ourred, so execute the error callback
} else {
options.onError();
}
// Call the pletion callback
options.onComplete();
// Clean up after ourselves, to avoid memory leaks
xml = null;
}
};
// Establish the connection to the server
xml.send();
// Determine the suess of the HTTP response
function httpSuess(r) {
try {
// If no server status is provided, and we're actually
// requesting a local file, then it was suessful
return !r.status && location.protocol == "file:" ||
// Any status in the 200 range is good
( r.status >= 200 && r.status < 300 ) ||
// Suessful if the document has not been modified
r.status == 304 ||
// Safari returns an empty status if the file has not been modified
navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined";
} catch(e){}
// If checking the status failed, then assume that the request failed too
return false;
}
// Extract the correct data from the HTTP response
function httpData(r,type) {
// Get the content-type header
var ct = r.getResponseHeader("content-type");
// If no default type was provided, determine if some
// form of XML was returned from the server
var data = !type && ct && ct.indexOf("xml") >= 0;
// Get the XML Document object if XML was returned from
// the server, otherwise return the text contents returned by the server
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the specified type is "script", execute the returned text
// response as if it was JavaScript
if ( type == "script" )
eval.call( window, data );
// Return the response data (either an XML Document or a text string)
return data;
}
}
在同等目录中,我们可以建立一个rss.xml文件,用这个函数来访问。
rss.xml如下
<titles>
<title>
缘份
</title>
<title>
月亮
</title>
<title>
缘份月亮
</title>
</titles>
再建立一个html文档,调用它,就能看到rss.xml中的内容就能被访问到。
整体看看,其实真的比较简洁和简单。不仅是能访问xml格式文件,html,.js格式的文件都可以调用的;
这些都可以在本地建立对应的文件,进行调用,都可以实现。
代码如下:
// A generic function for performming AJAX requests
// It takes one argument, which is an object that contains a set of options
// All of which are outline in the ments, below
function ajax( options ) {
// Load the options object with defaults, if no
// values were provided by the user
options = {
// The type of HTTP Request
type: options.type || "POST",
// The URL the request will be made to
url: options.url || "",
// How long to wait before considering the request to be a timeout
timeout: options.timeout || 5000,
// Functions to call when the request fails, sueeds,
// or pletes (either fail or sueed)
onComplete: options.onComplete || function(){},
onError: options.onError || function(){},
onSuess: options.onSuess || function(){},
// The data type that'll be returned from the server
// the default is simply to determine what data was returned from the
// and act aordingly.
data: options.data || ""
};
// Create the request object
var xml = new XMLHttpRequest();
// Open the asynchronous POST request
//xml.open("GET", "/some/url.cgi", true);
xml.open("GET",options.url, true);
// We're going to wait for a request for 5 seconds, before giving up
var timeoutLength = 5000;
// Keep track of when the request has been suesfully pleted
var requestDone = false;
// Initalize a callback which will fire 5 seconds from now, cancelling
// the request (if it has not already ourred).
setTimeout(function(){
requestDone = true;
}, timeoutLength);
// Watch for when the state of the document gets updated
xml.onreadystatechange = function(){
// Wait until the data is fully loaded,
// and make sure that the request hasn't already timed out
if ( xml.readyState == 4 && !requestDone ) {
// Check to see if the request was suessful
if ( httpSuess( xml ) ) {
// Execute the suess callback with the data returned from the server
options.onSuess( httpData( xml, options.type ) );
// Otherwise, an error ourred, so execute the error callback
} else {
options.onError();
}
// Call the pletion callback
options.onComplete();
// Clean up after ourselves, to avoid memory leaks
xml = null;
}
};
// Establish the connection to the server
xml.send();
// Determine the suess of the HTTP response
function httpSuess(r) {
try {
// If no server status is provided, and we're actually
// requesting a local file, then it was suessful
return !r.status && location.protocol == "file:" ||
// Any status in the 200 range is good
( r.status >= 200 && r.status < 300 ) ||
// Suessful if the document has not been modified
r.status == 304 ||
// Safari returns an empty status if the file has not been modified
navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined";
} catch(e){}
// If checking the status failed, then assume that the request failed too
return false;
}
// Extract the correct data from the HTTP response
function httpData(r,type) {
// Get the content-type header
var ct = r.getResponseHeader("content-type");
// If no default type was provided, determine if some
// form of XML was returned from the server
var data = !type && ct && ct.indexOf("xml") >= 0;
// Get the XML Document object if XML was returned from
// the server, otherwise return the text contents returned by the server
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the specified type is "script", execute the returned text
// response as if it was JavaScript
if ( type == "script" )
eval.call( window, data );
// Return the response data (either an XML Document or a text string)
return data;
}
}
在同等目录中,我们可以建立一个rss.xml文件,用这个函数来访问。
rss.xml如下
代码如下:
<titles>
<title>
缘份
</title>
<title>
月亮
</title>
<title>
缘份月亮
</title>
</titles>
再建立一个html文档,调用它,就能看到rss.xml中的内容就能被访问到。
整体看看,其实真的比较简洁和简单。不仅是能访问xml格式文件,html,.js格式的文件都可以调用的;
这些都可以在本地建立对应的文件,进行调用,都可以实现。
编程语言
- 如何快速学会编程 如何快速学会ug编程
- 免费学编程的app 推荐12个免费学编程的好网站
- 电脑怎么编程:电脑怎么编程网咯游戏菜单图标
- 如何写代码新手教学 如何写代码新手教学手机
- 基础编程入门教程视频 基础编程入门教程视频华
- 编程演示:编程演示浦丰投针过程
- 乐高编程加盟 乐高积木编程加盟
- 跟我学plc编程 plc编程自学入门视频教程
- ug编程成航林总 ug编程实战视频
- 孩子学编程的好处和坏处
- 初学者学编程该从哪里开始 新手学编程从哪里入
- 慢走丝编程 慢走丝编程难学吗
- 国内十强少儿编程机构 中国少儿编程机构十强有
- 成人计算机速成培训班 成人计算机速成培训班办
- 孩子学编程网上课程哪家好 儿童学编程比较好的
- 代码编程教学入门软件 代码编程教程