Ajax 核心框架函数及例子

所属分类: 网络编程 / AJAX相关 阅读数: 386
收藏 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格式的文件都可以调用的;
这些都可以在本地建立对应的文件,进行调用,都可以实现。
更多精彩内容其他人还在看

理解jquery ajax中的datatype属性选项值

jquery中ajax的dataType属性用于指定服务器返回的数据类型,如果不指定,jQuery 将自动根据HTTP包MIME信息来智能判断,如果datatype选项不填写的话,会将返回的数据当成字符串处理。
收藏 0 赞 0 分享

基于Jquery ajax技术实现间隔N秒向某页面传值

这篇文章给大家介绍jquery ajax技术实现每隔一段时间向某页面传值,以及setinterval()方法的语法介绍,对本文感兴趣的朋友可以参考下
收藏 0 赞 0 分享

通过Ajax两种方式讲解Struts2接收数组表单的方法

使用struts2表单传值,可以传一个或者是作为一个对象的各个属性传,都非常灵活便捷。但是如果我们需要传一个数组并希望struts正确接收,该怎么处理呢?接下来,通过本文给大家介绍通过Ajax两种方式讲解Struts2接收数组表单的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

基于Jquery.history解决ajax的前进后退问题

本文主要给大家介绍基于Jquery.history解决ajax的前进后退问题,涉及到jquery前进后退相关方面的知识,本文内容经典,非常具有参考价值,特此把jquery前进后退相关知识分享在脚本之家网站供大家参考
收藏 0 赞 0 分享

使用HTML5中postMessage知识点解决Ajax中POST跨域问题

这篇文章主要介绍了使用HTML5中postMessage知识点解决Ajax中POST跨域问题的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

谈谈你对aja的理解(一、二)

Ajax是Asynchronous Javascript And XML的缩写,其作用通过Ajax可以使用Javascript语句来调用XMLHttpRequest对象,直接与服务器进行通讯,可以在不重载页面的情况下与服务器交换数据。
收藏 0 赞 0 分享

关于ajax对象一些常用属性、事件和方法大小写比较常见的问题总结

最近比较空闲,于是抽个时间整理些关于ajax方法的东东。在项目中经常发现ajax板块好多问题都是属性,方法,事件大小写不区分问题,最终导致了程序运行出现麻烦,下面给大家介绍关于ajax对象一些常用属性、事件和方法大小写比较常见的问题总结
收藏 0 赞 0 分享

Ajax请求session失效该如何解决

HTML + Servlet + Filter + jQuery 一般来说我们的项目都有登录过滤器,一般请求足以搞定。但是AJAX却是例外的,所以解决方法是设置响应为session失效。
收藏 0 赞 0 分享

编写轻量ajax组件02--浅析AjaxPro

ajaxpro虽然是一个比较老的组件,不过实现思想和源码还是很有借鉴价值的。接下来通过本篇文章给大家介绍编写轻量ajax组件02--浅析AjaxPro,感兴趣的朋友可以参考下
收藏 0 赞 0 分享

编写轻量ajax组件01-与webform平台上的各种实现方式比较

这篇文章主要介绍了编写轻量ajax组件01-与webform平台上的各种实现方式比较,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多