Ajax 核心框架函数及例子

所属分类: 网络编程 / AJAX相关 阅读数: 328
收藏 0 赞 0 分享
核心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 comments, 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, succeeds,
// or completes (either fail or succeed)
onComplete: options.onComplete || function(){},
onError: options.onError || function(){},
onSuccess: options.onSuccess || 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 accordingly.
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 succesfully completed
var requestDone = false;
// Initalize a callback which will fire 5 seconds from now, cancelling
// the request (if it has not already occurred).
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 successful
if ( httpSuccess( xml ) ) {
// Execute the success callback with the data returned from the server
options.onSuccess( httpData( xml, options.type ) );
// Otherwise, an error occurred, so execute the error callback
} else {
options.onError();
}
// Call the completion callback
options.onComplete();
// Clean up after ourselves, to avoid memory leaks
xml = null;
}
};
// Establish the connection to the server
xml.send();
// Determine the success of the HTTP response
function httpSuccess(r) {
try {
// If no server status is provided, and we're actually
// requesting a local file, then it was successful
return !r.status && location.protocol == "file:" ||
// Any status in the 200 range is good
( r.status >= 200 && r.status < 300 ) ||
// Successful 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格式的文件都可以调用的;
这些都可以在本地建立对应的文件,进行调用,都可以实现。
更多精彩内容其他人还在看

ajax中文乱码问题解决方案

ajax中文乱码问题在中文中经常会出现这种问题,其实只要稍加注意就不会出现ajax中文乱码这回事情了,接下来为大家详细介绍下如何解决这类问题
收藏 0 赞 0 分享

jquery ajax实现批量删除具体思路及代码

回调函数,在请求完成后需要进行的操作:此处是把选中的checkbox去掉,接下来为大家详细介绍下,感兴趣的朋友可以参考下哈,希望对你有所帮助
收藏 0 赞 0 分享

JQuery+ajax实现批量上传图片(自写)

jquery+ajax方式实现单张图片上传的代码是可以搜的到,实现批量上传图片的程序却没搜索到于是自己写了个,感兴趣的朋友可以参考下
收藏 0 赞 0 分享

利用Ajax实现在脚本里传值实例介绍

Ajax实现在脚本里传值可以解决实际上的一些问题,本文实现了一下,感兴趣的朋友可以参考下,希望可以帮助到你
收藏 0 赞 0 分享

jQuery+Ajax实现表格数据不同列标题排序(为表格注入活力)

CSS也使得表格的布局越来越光彩耀人。但是,无论如何,都掩饰不了那些包装下的死板,接下来为大家介绍下让那些死板的数据 更具有可读性、可用性
收藏 0 赞 0 分享

jQery ajax——load()方法示例介绍

load(url,[data],[callback])url:加载的页面地址;data: 可选项,发送到服务器的数据,格式是key/value;callback:可选项,回调函数,示例代码如下
收藏 0 赞 0 分享

滑轮滚动到页面底部ajax加载数据配合jsonp实现探讨

滚动下拉到页面底部加载数据是很多瀑布流网站的做法,那来看看配合jsonp是如何实现的吧,小菜总结记录之用特在此与大家一起分享,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

ajax 登录功能简单实现(未连接数据库)

未连接数据库下实现ajax 登录功能判断登陆成功与失败,喜欢ajax的朋友可以参考下哈,希望对大家有所帮助
收藏 0 赞 0 分享

AJAX和WebService实现邮箱验证(无刷新验证邮件地址是否合法)

首先在项目里面添加服务引用,验证 Email 地址是否正确(邮件地址合法、只是域名正确、邮件服务器没有找到等等)感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

AJAX和三层架构实现分页功能具体思路及代码

本文涉及到AJAX和三层架构方面的知识,在学习分页的同时也巩固了一下它们的相关知识,适合初学者的你
收藏 0 赞 0 分享
查看更多