Ajax的使用方法

本文详细介绍了Ajax的基本使用方法,包括javaScript原生实现的get和post请求,以及通过jQuery简化Ajax调用的方式。同时,文章还提供了JSON数据解析的示例。

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

Ajax

一、 javaScript原生使用Ajax

1.get方法

//1.创建对象 兼容处理
var xhr = null;
//处理低版本IE不兼容问题
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.准备发送
xhr.open('get','xxx.php?username=' + usernameValue ,true);
//3.执行发送
xhr.send(null);
//4.回调
xhr.onreadystatechange = function () {
    /*xhr.readyState == 4  是表示数据解析完成,后台处理完成了。
       xhr.status == 200 是表示处理的结果是OK的。响应成功*/
    if (xhr.readyState == 4){
        if(xhr.status == 200){
            //返回结果
            var result = xhr.responseText;
            console.log(result); 
        }
    }
};

2.post方法

//#1.创建对象 兼容性
var xhr = null;
//处理低版本IE不兼容问题
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
//#2.准备发送
xhr.open('post','xxx.php',true);

var param = 'phone=' + phoneValue;
//设置响应头
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
//#3.执行发送
xhr.send(param);

//#4.回调函数
xhr.onreadystatechange = function () {
    if(xhr.readyState == 4){
        if(xhr.status ==200){
            var result = xhr.responseText;
            console.log(result);
        }
    }
}

open()方法后面的参数truefalse,表示异步和同步,同步(false)就是先吃完饭才能看电视,异步(true)就是边吃饭边看电视**

二、 jQuery中的Ajax

1.基本使用方法

$.ajax({
    url: 'xxx.php',
    type: 'get',
    beforeSend: function(xhr){
        console.log(xhr);
    },
    success: function (res) {
        console.log(res);
    },
    error:function (xhr) {
        console.log(xhr);
    },
    complete:function (xhr) {
        console.log(xhr);
    }
});

post方式只需把type值改成 post就行

2.快捷方式

$.get('xxx.php',{id:1},function (res) {
    console.log(res);
});

$.post('xxx.php',{id:1},function (res) {
    console.log(res);
});

以上是getpost两种方式

3.解析Json格式

$.getJSON('xxx.php',{id:1},function (res) {
    console.log(res);
});

或者在放置json格式文件的php中进行申明头部

<?php
$zhangsan = array(
    'name' =>'张三',
    'age'  =>18
);
//格式
header('Content-Type:application/json');
echo json_encode($zhangsan);
?>

转载于:https://www.cnblogs.com/hunterxing/p/9720037.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值