ajax基本代码

js写法

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<input type="button" name="">
</body>
</html>
<script>
	document.querySelector("input").onclick=function(){
		var xhr =new XMLHttpRequest(); //创建异步对象,这里的()别忘记了
		xhr.open("post","xxx.php");  //设置请求行:请求的方式(post/get),请求的url   (get:会在网址栏中出现结果,易于测试但安全性不高。post无这种问题)
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//请求头,在post请求方式中必须有并且特定这种写法
		xhr.onreadystatechange=function(){   //回调函数,还有一种onload写法 //xhr.onload=function(){}
			if(this.readyState==4&&this.status==200){  //状态等于4时响应完成,但页面404时仍可接收到响应,所以这里要status(页面状态)==200,既页面正常才给接收响应
				console.log(this.readyState);   //值是4
				console.log(this.responseText);
			}
		};
		xhr.send("name=heihei&skill=haha&age=15&sex=man");  
		//(请求主体)发送请求,post请求方式的请求信息写在请求主体里,就是这里(这里已经写了)
		//get请求方式的请求信息写在请求行里,如 xhr.open("get","xxx.php?name=heihei&skill=haha&age=15&sex=man")```
	}
</script>

jQuery写法

$(function(){
		$("input").on("click",function(){
		$.ajax({
				url:"./callback.php",		//请求地址
				type:"get",			//请求方式
			data:"name=林子闲&wife=乔韵",			//这里的data:发送给服务器的请求数据
				success:function(data){  //回调函数:数据请求成功之后调用
					console.log(data);  				 //这里的data:从服务器发送回来的数据
				},
				// dataType:"json",
				//dataType:"xml"     设置请求回来的数据格式是json还是xml.								
									//也可以在php文件里设置数据格式    header("content-type:application/json;charset=utf-8");
			})
		})
	})
posted @ 2019-05-01 22:23  huihuihero  阅读(5101)  评论(0编辑  收藏  举报