<!DOCTYPE HTML>
<html>
<head>
<title>please enter your title</title>
<meta charset="utf-8">
<meta name="Author" content="年轻人">
<style type='text/css'>
*{ margin:0; padding:0;}
</style>
</head>
<body>
<input type="button" id='btn' value="button" />
<script type="text/javascript">
/*
ajax: Asynchronous Javascript And XML
异步的js和XML
不需要刷新页面就可以传送接收数据
*/
var oBtn = document.getElementById('btn');
/*
var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
xhr.open( 'post' , 'ost.php' , true);
xhr.setRequestHeader('content-type' , 'application/x-www-form-urlencoded');
xhr.send('user=afei&pwd=123456');
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 )
{
if ( xhr.status >= 200 && xhr.status<300 )
{
alert( xhr.responseText );
}
else
{
alert('请求不成功,错误代码' + xhr.status)
}
}
}
*/
/*
post方法传数据:
send( );
*/
/*
方法 getpost
路径
是否异步
数据
请求成功做的事
请求不成功做的事
*/
oBtn.onclick = function(){
ajax({
method : 'post',
url : 'post.php',
data : 'user=afei&pwd=123456',
success : function(d){
alert( d )
}
});
}
function ajax( aJson ){
var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
var method = aJson.method || 'get',
url = aJson.url,
aysn = aJson.aysn || true,
data = aJson.data || '',
success = aJson.success,
error = aJson.error;
if ( method.toLowerCase() == 'get' )
url += '?'+data+'&'+new Date().getTime();
xhr.open( method, url , aysn);
xhr.setRequestHeader('content-type' , 'application/x-www-form-urlencoded');
xhr.send(data);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 )
{
if ( xhr.status >= 200 && xhr.status<300 )
{
success && success(xhr.responseText);
}
else
{
error && error();
}
}
}
}
</script>
</body>
</html>
js原生ajax实例详解
最新推荐文章于 2025-02-24 13:36:17 发布