ajax请求的几种方式

来源:互联网 发布:pspice仿真软件下载 编辑:程序博客网 时间:2024/05/21 10:28

1:普通请求:

get的数据,直接在请求的url中添加即可

<script type="text/javascript">    // 创建XMLHttpRequest 对象    var xml = new XMLHttpRequest();    // 设置跟服务端交互的信息    xml.open('get','01.ajax.php?name=fox');    xml.send(null);    // get请求这里写null即可    // 接收服务器反馈    xhr.onreadystatechange = function () {        // 这步为判断服务器是否正确响应        if (xhr.readyState == 4 && xhr.status == 200) {            // 打印响应内容            alert(xml.responseText);        }     };</script>
  • 示例代码:POST
<script type="text/javascript">    // 异步对象    var xhr = new XMLHttpRequest();    // 设置属性    xhr.open('post', '1index.php' );    // 如果想要使用post提交数据,必须添加    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");    // 将数据通过send方法传递    xhr.send('name=fox&age=18');    // 发送并接受返回值    xhr.onreadystatechange = function () {    // 这步为判断服务器是否正确响应    if (xhr.readyState == 4 && xhr.status == 200) {           alert(xhr.responseText);         }     };</script>



2:jquery的AJAX

$.ajax({
url: '1index.php',
type: 'POST',//GET
async: true,//或false,是否异步
data: {
name: 'yang',age: 25
},
timeout: 5000,//超时时间
dataType: 'json',//返回的数据格式:json/xml/html/script/jsonp/text
beforeSend: function (xhr) {
console.log(xhr)
console.log('发送前')
},
success: function (data,textStatus, jqXHR) {
console.log(data) //自动json数据
console.log(textStatus)
console.log(jqXHR)
},
error: function (xhr,textStatus) {
console.log('错误')
console.log(xhr)
console.log(textStatus)
},
complete: function () {
console.log('结束')
}
})




<div class="btn">点我</div>
<script>
var add=document.querySelectorAll('.btn')[0];
add.onclick=function(){
var xhr =new XMLHttpRequest();
xhr.open('post','1index.php' );
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 将数据通过send方法传递
xhr.send('name=12&age=18');
// 发送并接受返回值
xhr.onreadystatechange =function () {
// 这步为判断服务器是否正确响应
if (xhr.readyState ==4 && xhr.status ==200) {
var res=JSON.parse(xhr.responseText);
var list=res.data.catname;
add.innerHTML=list;
}
};
}
<?php
// require 'view/admin/catadd.html';
$add=['cat_id' =>'1','catname' =>'人生'];
function response($data=null,$status=200,$message='success'){
header('Content-type: application/json');

$arr = array(
'code'=>$status,
'data'=>$data,
'message'=>$message,
);

echo json_encode($arr);


exit();
}
response($add);

?>
自己写的,能完美运行!