ajax的3种请求方式

本文深入探讨了Ajax的三种请求方式:GET、POST和使用$.ajax()方法的POST请求。通过具体的HTML和JavaScript代码示例,展示了如何在前端通过按钮触发不同的请求,并在后端PHP文件中处理这些请求。此外,还介绍了如何指定服务器返回JSON格式数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                          ajax的3种请求方式 get()  post() ajax()

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>ajax的3种请求方式</title>
	<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<input id="user" type="text" name="username">
<button id="btn1">get</button>
<button id="btn2">post</button>
<button id="btn3">ajax</button>
<script type="text/javascript">
	// get
	$('#btn1').click(function(){
		$.get('test.php',{'user':$('#user').val()},function(text){
			console.log(text);
		})
	})
	// post
	$('#btn2').click(function(){
		$.post('test.php',{'user':$('#user').val()},function(text){
			console.log(text);
		})
	})
	// ajax
	$('#btn3').click(function(){
		$.ajax({
			type:'POST',
			url:'test.php',
			data:{
				'user':$('#user').val()
			},
			success:function(text){
				console.log(text);
			}
		})
	})
</script>
</body>
</html>

test.php::

<?php
$user = $_REQUEST['user'];
echo $user;
?>

可以指定服务端返回的数据类型:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>ajax的3种请求方式</title>
	<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<input id="user" type="text" name="username">
<button id="btn1">get</button>
<button id="btn2">post</button>
<button id="btn3">ajax</button>
<script type="text/javascript">
	// get
	$('#btn1').click(function(){
		$.get('test.php',{'user':$('#user').val()},function(text){
			if(text.code==-1) console.log(text.msg);
		},'json')  //指定返回类型 数据返回时会自动把json转化为一个对象
	})
	// post
	$('#btn2').click(function(){
		$.post('test.php',{'user':$('#user').val()},function(text){
			if(text.code==-1) console.log(text.msg);
		},'json') //指定返回类型
	})
	// ajax
	$('#btn3').click(function(){
		$.ajax({
			type:'POST',
			url:'test.php',
			data:{
				'user':$('#user').val()
			},
			success:function(text){
				if(text.code==-1) console.log(text.msg);
			},
			dataType:'json' //指定返回类型
		})
	})
</script>
</body>
</html>

test.php:

<?php
$user = $_REQUEST['user'];
if(empty($user)){
//json_encode将数组转化为json字符串
	echo (json_encode(array('code'=>-1,'msg'=>'用户名不能为空')));
}
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值