XHR,原生js方式
获取XHR对象
var XHR = false ;
if ( window. XMLHttpRequest) {
XHR = new XMLHttpRequest ( ) ;
} else {
XHR = new ActiveXObject ( 'Microsoft.XMLHTTP' ) ;
}
发送数据示例
if ( XHR != false ) {
var uri= "sign.action" ;
XHR . open ( "post" , uri, true ) ;
XHR . setRequestHeader ( "Content-type" , "application/x-www-form-urlencoded" ) ;
XHR . send ( "date=" + date) ;
XHR . onreadystatechange= signResult;
}
else
alert ( "XHR is NULL" ) ;
接收数据示例
function signResult ( ) {
if ( XHR . readyState== 4 && XHR . status== 200 ) {
if ( ! XHR . responseText)
alert ( "..." )
else {
...
}
}
}
JQuery的方式
get、post方式
$. get ( action, function ( result, statu) {
switch ( statu) {
case "success" :
...
}
} , "json" ) ;
$. post ( action, function ( result, statu) {
switch ( statu) {
case "success" :
...
}
} , "json" ) ;
ajax方式
$. ajax ( {
url: url,
type: "POST" ,
data: data,
timeout: 30000 ,
dataType: 'json' ,
success: success,
error: function ( xhr, status) {
console. log ( url+ "数据获取错误:" + status) ;
}
} )
附:获取项目根目录的方法
function getRootPath_dc ( ) {
var pathName = window. location. pathname. substring ( 1 ) ;
var webName = pathName == '' ? '' : pathName. substring ( 0 , pathName. indexOf ( '/' ) ) ;
if ( webName == "" ) {
return window. location. protocol + '//' + window. location. host;
}
else {
return window. location. protocol + '//' + window. location. host + '/' + webName;
}
}