原生javaScript实现Ajax 和 jQuery实现Ajax

栏目: jQuery · 发布时间: 6年前

内容简介:作者后台使用的是

作者后台使用的是 php 语言,所以这里以 php 后台Api为例子,不影响学习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 值改成 get 就行

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

阿里巴巴正传:我们与马云的“一步之遥”

阿里巴巴正传:我们与马云的“一步之遥”

方兴东、刘伟 / 江苏凤凰文艺出版社 / 2015-1 / 45.00

十几年来,方兴东与马云每年一次,老友聚首,开怀畅谈,阿里上市前,作者再次与马云深度对话,阿里上市前的布局,深入探讨了一系列人们关心的话题。 本书忠实记录了阿里壮大、马云封圣的历史。作者通过细致梳理和盘点,对阿里巴巴的15年成长史进行了忠实回顾。从海博翻译社到淘宝网,从淘宝商城到天猫,从支付宝到阿里云计算,从拉来软银的第一笔投资到纽交所上市,作者对其中涉及到的人物、细节都有生动展现;对于马云、......一起来看看 《阿里巴巴正传:我们与马云的“一步之遥”》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具