1+ ! function ( $ ) {
2+ "use strict" ;
3+ //变量定义与赋值
4+ var oldUrl = location . href , newUrl , urlData ;
5+ //主体方法
6+ var AjaxLoadPage = function ( element , options ) {
7+ var _this = this ;
8+ //默认赋值
9+ _this . options = $ . extend ( { } , AjaxLoadPage . DEFAULTS , options ) ;
10+ //处理打开事件
11+ $ ( element ) . on ( _this . options . trigger , _this . options . bindNodes , function ( ) {
12+ if ( this . tagName === "A" ) {
13+ newUrl = $ ( this ) . attr ( "href" ) ;
14+ urlData = { } ;
15+ } else if ( this . tagName === "FORM" ) {
16+ newUrl = $ ( this ) . attr ( "action" ) ;
17+ urlData = $ ( this ) . serialize ( ) ;
18+ } else {
19+ return false ;
20+ }
21+ _this . LoadPage ( newUrl , urlData , _this . options ) ;
22+ event . preventDefault ( ) ;
23+ } ) ;
24+ } ;
25+ //加载页面方法
26+ AjaxLoadPage . prototype . LoadPage = function ( url , data ) {
27+ var _this = this ;
28+ _this . options . before . call ( ) ;
29+ //Ajax 加载数据
30+ $ ( "<div/>" ) . load ( url , data , function ( response , status , xhr ) {
31+ if ( status === "success" ) {
32+ //替换数据
33+ var parseHTML = $ . parseHTML ( response ) ;
34+ var jqHTML = $ ( "<div>" ) . append ( $ ( parseHTML ) ) ;
35+ $ . each ( _this . options . replaceNodes , function ( oldNode , newNode ) {
36+ $ ( oldNode ) . replaceWith ( jqHTML . find ( newNode ) ) ;
37+ } ) ;
38+ //替换页面状态
39+ history . pushState ( null , document . title , oldUrl ) ;
40+ var result , title ;
41+ if ( ( result = response . match ( / < t i t l e > ( [ \s \S ] + ) < \/ t i t l e > / i) ) !== null ) {
42+ title = result [ 1 ] ;
43+ } else {
44+ title = document . title ;
45+ }
46+ document . title = title ;
47+ //调用完成方法
48+ _this . options . finished . call ( ) ;
49+ } else if ( status === "error" ) {
50+ _this . options . error . call ( xhr . status ) ;
51+ }
52+ } ) ;
53+ } ;
54+ //默认参数
55+ AjaxLoadPage . DEFAULTS = {
56+ bindNodes : "" ,
57+ replaceNodes : { } ,
58+ trigger : "click submit" ,
59+ before : function ( ) {
60+ } ,
61+ finished : function ( ) {
62+ } ,
63+ error : function ( ) {
64+ }
65+ } ;
66+ var old = $ . fn . AjaxLoadPage ;
67+ $ . fn . AjaxLoadPage = function ( option ) {
68+ return this . each ( function ( ) {
69+ var $this = $ ( this ) ;
70+ var data = $this . data ( 'AjaxLoadPage' ) ;
71+ var options = ( typeof option === 'object' ) && option ;
72+ if ( ! data ) $this . data ( 'AjaxLoadPage' , ( data = new AjaxLoadPage ( this , options ) ) ) ;
73+ } )
74+ } ;
75+ $ . fn . AjaxLoadPage . Constructor = AjaxLoadPage ;
76+ $ . fn . AjaxLoadPage . noConflict = function ( ) {
77+ $ . fn . AjaxLoadPage = old ;
78+ return this ;
79+ } ;
80+ } ( jQuery ) ;
0 commit comments