关于原生js和jquery的AJAX实现

 一、HTML与CSS

<div class="container">
		<h2>ajax</h2>
		<div class="message">hello world</div>
		<button class="btn">getAjax</button>
</div>
<style type="text/css">
		*{
			padding: 0;
			margin: 0;

		}
		.container{
			height: 100vh;
			display: flex;
			flex-direction:column;
			justify-content:center;
			align-items:center;
		}
		.message{
			width: 300px;
			margin-top: 2rem;
			padding: 10px;
			background-color:#888;
		}
		button{
			margin-top: 2rem;
			padding: 10px 20px;
			background-color:#123456;
			color:#fff;
			border-radius:5px;
			outline: none;
			border: none;
			cursor:pointer;
		}
		button:hover{
			background-color:#654321;
		}
	</style>

效果: 

 

二、AJAX实现

[
	{
		"id":1,
		"name":"用户一",
		"age":18
	},
	{	"id":2,
		"name":"用户二",
		"age":18
	},
	{
		"id":3,
		"name":"用户三",
		"age":18
	}
]

                                                                                                                                                                                 my.json


<?php

 $name=$_POST['json'];
 echo $name;


?>

                                                                                                                                                                                 a.php


 

 

 

1.原生js获取数据


    	    document.getElementsByClassName('btn')[0].onclick=function(){
			var xml=new XMLHttpRequest();
			xml.open('GET','./json/my.json',true);
			xml.send();
			xml.onreadystatechange=function(){
				if(xml.readyState==4&&xml.status==200){
					var obj=JSON.parse(xml.responseText);
					var html='';
					html += "<div class='div'><table border=1>";
					obj.forEach((v,i)=>{
						html+="<tr>";
						for(var key in v){
							html+="<td>"+v[key]+"</td>";
							
						}
						html+="</tr>";
					})
					html+="</div></table>";


					document.getElementsByClassName('message')[0].innerHTML=html;
					console.log(JSON.parse(xml.responseText));
				}
			}
		}

 JSON.stringify()的作用是将 JavaScript 对象转换为 JSON 字符串,而JSON.parse()可以将JSON字符串转为一个对象。

效果:

2.原生js发送数据

        var data = {
			"student1":"one",
			"student2":"two"};
		
		document.getElementsByClassName('btn')[0].onclick=function(){
			var xml=new XMLHttpRequest();
			xml.open('POST','./json/a.php',true);
			 xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			xml.send("json="+JSON.stringify(data));
			xml.onreadystatechange=function(){
			  if(xml.readyState==4 && xml.status==200){
			    document.getElementsByClassName('message')[0].innerHTML=xml.responseText;
			    console.log(JSON.parse(xml.responseText));
			  }
			};
		}

如果用post发送数据需要设置响应头,‘application/x-www-form-urlencoded’是表单的请求头,数据以key1=val1&key2=val2 的方式进行编码。

3.jquery获取数据

$('.btn').click(function(){
			$.ajax({
				url:'./json/my.json',
				type:'get',
				data:'',
				dataType:'json',
				success:function(re){
					console.log(re);
					$('.message').html(JSON.stringify(re));
				}
			})
		})

jq封装后的ajax获取成功后得到的是对象,而不是json字符串。 

4.jquery发送数据

var data = {
			"student1":"one",
			"student2":"two"};
		$('.btn').click(function(){
			console.log('click');
			$.ajax({
				url:'./json/a.php',
				type:'POST',
				data:"json="+JSON.stringify(data),
				dataType:'json',
				contentType: "application/x-www-form-urlencoded",
				success:function(re){
					console.log(re);
					$('.message').html(JSON.stringify(re));
				}
			})
		})

contentType: "application/x-www-form-urlencoded"  如果默认要使用表单方式提交,可以不加,因为jq封装的ajax默认是表单提交请求头的。

 

----------------------------------------------------------------------------------------请求头

application/x-www-form-urlencoded发送前编码所有字符(默认),提交的数据按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码。大部分服务端语言都对这种方式有很好的支持。
multipart/form-data不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须将 enctype设为 multipart/form-data。
application/json作为请求头告诉服务端消息主体是序列化的JSON字符串。除低版本的IE,基本都支持。
text/plain空格转换为 “+” 加号,但不对特殊字符编码。

 

如果ajax使用contentType: "application/json"响应头来发送数据的话,如下:

var data = {
			"student1":"one",
			"student2":"two"};
		$('.btn').click(function(){
			console.log('click');
			$.ajax({
				url:'./json/a.php',
				type:'POST',
				data:JSON.stringify(data),
				dataType:'json',
				contentType: "application/json",
				success:function(re){
					console.log(re);
					$('.message').html(JSON.stringify(re));
				}
			})
		})

然而这样就无法使用$_POST获取数据了,需要使用file_get_contents("php://input")。

注:contentType: "application/json"只能发送字符串。

<?php

  $name=file_get_contents("php://input");
 echo $name;


?>

 php://input 是个可以访问请求的原始数据的只读流。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值