jqAjax Ajax请求

后台php文件一定不能有<-- -->这样的注释和除了echo json_encode()外其他的
echo ,否则无法传输!!!

前台:

Ajax
	前后端交互,借助xmlHttpRequest对象来构建

get无参请求:一般用来向后台获取数据使用,不会发送给后台任何内容
get带参请求:一般像贴吧、社区等需要根据页码或指定属性获取数据时使用,参数一般都比较小
post请求:一般用于登录,注册等保密性较高的使用

jqeury Ajax写法

	get无参请求

		$.ajax({
			type:'get',
			url:'发送到的后台地址',
			dataType:'json',  //表示后台返回的格式

			success:function(参数){  //表示接收后台数据的函数
				方法体;
			}
		});
	
	get请求有参(及传入键值对到url?后面)

		$.ajax({
			type:'get',
			url:'发送到的后台地址'+"?"+键值对,
			dataType:'json',  //表示后台返回的格式

			success:function(参数){  //表示接收后台数据的函数
				方法体;
			}
		});

	post请求

		$.ajax({
			type:'post',
			url:'发送到的后台地址',
			dataType:'json',  //表示后台返回的格式
			//post独有的字段
			data:{
				json格式数据
			}
			success:function(参数){  //表示接收后台数据的函数
				方法体;
			}
		});

后台:

$_GET 这个内置对象,表示接收到的前端发送过来的get请求参数,及url地址中?后的键值对
$_POST 这个内置对象,表示从前端发送过来的post请求数据
echo 代表返回给前端的指定数据,必须是json类型
json_encode(对象/...)  来将数组或对象等复杂类型转换成json格式

代码示例:

前台:

<html>
<head>
	<meta charset="utf-8">
	<title>Ajax</title>
	<script src="jquery-3.4.1.js"></script>
<body>
	<span>用户名:</span><input type="text" class="uname"><br/>
	<span>密码:</span><input type="password" class="pwd"><br/>
	<button>get无参请求</button>
	<button>get带参请求</button>
	<button>post请求</button>

	<script >
	var $unameInput=$(".uname");
	var $pwdInput=$(".pwd");
	var $btns=$("button");
	//jquery中Ajax写法
	
	//get无参写法
	$btns.eq(0).click(function(){
			$.ajax({
				type:'get',  //请求方式
				url:'3.php',		//发送到的后台地址
				dataType:'json',    //表示后台返回的格式
				success:function(res)  //后台返回数据时接受数据的函数
				{
					console.log(res);
					console.log(res.msg);
					console.log(res.info);
				}
			})
		});

	//get有参写法
	$btns.eq(1).click(function(){
		$.ajax({
			type:'get',
			url:'3.php?uname='+$unameInput.val()+"&password="+$pwdInput.val(),
			dataType:'json',
			success:function(res)
			{
				console.log(res);
				console.log(res['info']);
				console.log(res.info);
			}
		})

	});

	$btns.eq(2).click(function(){

			$.ajax({
				type:"post",
				url:'3.php',
				dataType:"json",
				//post请求独有的字段
				data:{
					uname:$unameInput.val(),
					upass:$pwdInput.val()
				},
				success:function(res){

					console.log(res['info']);
				}
			});

	});

	</script>

</body>
</head>
</html>

后台:

<?php
	
	$successArr=array('msg'=>'ok','info'=>'报到');
	echo json_encode($successArr); //转换成json发送给前台
	
	$arr=array('msg'=>'ok','info'=>$_GET);
	echo json_encode($arr);
	
	$arr=array('msg'=>"ok",'info'=>$_POST);
	echo json_encode($arr);

?>
发布了252 篇原创文章 · 获赞 3 · 访问量 3291

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/103589895