Ajax 核心框架函数及例子

 更新时间:2009年09月20日 18:51:23   作者:  
最近学习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 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系列第一篇之XHR对象

    深入理解ajax系列第一篇之XHR对象

    ajax是asynchronous javascript and XML的简写,中文翻译是异步的javascript和XML,这一技术能够向服务器请求额外的数据而无须卸载页面,会带来更好的用户体验
    2016-11-11
  • 将xml文件作为一个小的数据库,进行学生的增删改查的简单实例

    将xml文件作为一个小的数据库,进行学生的增删改查的简单实例

    下面小编就为大家带来一篇将xml文件作为一个小的数据库,进行学生的增删改查的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • AJAX实现无刷新检测用户名功能

    AJAX实现无刷新检测用户名功能

    这篇文章主要为大家详细介绍了AJAX实现无刷新用户名检测功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • ajax的json传值方式在jsp页面中的应用

    ajax的json传值方式在jsp页面中的应用

    ajax的json传值想必大家早有所耳闻了吧,本文介绍下jsp页面中json传值应用,感兴趣的你可以参考下哈,希望可以帮助到你
    2013-03-03
  • ajax实现服务器与浏览器长连接的功能

    ajax实现服务器与浏览器长连接的功能

    这篇文章主要介绍了ajax实现服务器与浏览器长连接的功能的相关资料,感兴趣的小伙伴们可以参考一下
    2016-04-04
  • ajax详解_动力节点Java学院整理

    ajax详解_动力节点Java学院整理

    这篇文章主要介绍了ajax详解,详细的介绍了Ajax 简史以及 基本用法,有兴趣的可以了解一下
    2017-07-07
  • Ajax邮箱、用户名唯一性验证实例代码

    Ajax邮箱、用户名唯一性验证实例代码

    这篇文章主要介绍了Ajax邮箱、用户名唯一性验证实例代码,需要的朋友可以参考下
    2017-10-10
  • Ajax获取页面被缓存的解决方法

    Ajax获取页面被缓存的解决方法

    常利用AJAX写一些页面无刷新的内容获取页面,这种方式很快捷也很方便,但其中有一个问题,就是如果两次提交的参数相同时,返回的内容只返回上次获取的内容,如果我们在第一次修改了参数,第二次再次调用却会发现页面根本没有改变。
    2008-09-09
  • Ajax 传递JSON实例代码

    Ajax 传递JSON实例代码

    虽然ajax全称是asynchronous javascript and XML。但目前使用ajax技术时,传递JSON已经成为事实上的标准。这篇文章主要介绍了Ajax 传递JSON实例代码,需要的朋友可以参考下
    2017-03-03
  • ajax来自动补全表单字段示例

    ajax来自动补全表单字段示例

    这篇文章主要介绍了如何使用ajax来自动补全表单字段,需要的朋友可以参考下
    2014-08-08

最新评论