ajax请求的几种方式

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);

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值