Ajax|day02-Ajax发送get和post请求、上传文件

it2024-04-17  52

Post发送数据

<!-- get方式提交数据 1. 数据存放在URL中 2. 数据安全性不好 3. 数据存放量有限(有一些浏览器或者服务器会限制或者忽略过长的URL) 但get方式提交测试方便 --> <!-- post方式提交 1. 提交的数据不再URL中,安全性更高 2. 浏览器端可以提交任意长度的数据,服务器端可以选择是否接受这些数据 3. 如果要上传文件,必须使用post --> <!-- post提交数据,需设置method=post --> <form action="02sent.php" method="post"> <input type="text" placeholder="你喜欢什么颜色" name="color"> <input type="text" placeholder="你喜欢什么动漫" name="dmName"> <input type="submit"> </form>

在php中使用$_POST获取提交的数据

上传文件

<!-- 提交方式 - post form表单 input type=file... --> <!-- 上传文件时,必须设置enctype属性为multipart/form-data application/x-www-form-urlencoded - 默认|发送前对所有字符编码 multipart/form-data - 不对字符编码,在使用包含文件上传控件的表单时,必须使用改值 text/plain - 空格转换为‘+’号,不对特殊字符编码 --> <form action="./02getFile.php" method="POST" enctype="multipart/form-data"> <input type="file" name="icon"> <input type="submit"> </form>

02getFile.php

<?php //超全局变量,用来接收文件 print_r($_FILES); /* Array( [icon] => Array( [name] => xxx.xx [type] => 文件类型 [tmp_name] => 文件路径(xxx.tmp 临时文件) php代码执行结束后,临时文件就被销毁 [error] => 0(错误编码) [size] => 文件大小 ) ) */ //文件时临时缓存的,执行完整个php后就会销毁,所以需要将临时文件复制进行存储 // move_uploaded_file(file,newloc) // 参数1 移动的文件 // 参数2 移动往何处 move_uploaded_file($_FILES['icon']['tmp_name'],'./files/'.$_FILES['icon']['name']); ?>

Ajax不刷新页面发送请求

//绑定事件 document.querySelector('input').onclick = function(){ //1. 创建对象 //创建 对象 异步对象 var xhr = new XMLHttpRequest(); //2. 设置请求行(get请求数据写在URL后面) //请求行 //get 请求 数据拼接在URL中 //request.php?xxx=*** xhr.open('get','request.php?name=haha'); //注册回调函数 xhr.onload = function(){ console.log("请求已响应!"); console.log(xhr.responseText) //获取返回的文本(响应头中的文本-响应报文) //修改页面的dom元素 document.querySelector('h3').innerHTML = xhr.responseText; } //3. 设置请求头(get可以省略,post不发送数据也可以省略) //请求头 //参数1 键名,参数2 值 // xhr.setRequestHeader('qqt','good good study!'); //get请求可以没有这个 //4. 请求主体发送(get请求为空,或者写null,post请求数据写在这里,如果没有数据,直接为空或者null) //请求主体 xhr.send(null); }

request.php

<?php echo $_GET['name']; ?>

Ajax发送POST请求

//点击事件 document.getElementsByTagName('input')[0].onclick = function(){ var xhr = new XMLHttpRequest(); xhr.open('post','02_06ajaxPost.php'); //如果使用post发送数据,必须设置此项 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') xhr.onload = function(){ console.log(xhr.responseText); } //post请求发送数据写在send()中 //key=value&key2=value2 xhr.send('name=kkk&age=19'); }
最新回复(0)