0
点赞
收藏
分享

微信扫一扫

AJAX(一)——初识AJAX 用原生和jQuery写GET和POST请求方法

善解人意的娇娇 2022-02-13 阅读 32

文章目录

什么是AJAX

AJAX是无需重新加载整个页面的前提下 , 更新部分页面
AJAX = 异步 JavaScript 和 XML

优缺点

优点 :

  • 不需要插件的⽀持,原⽣ js 就可以使⽤
  • ⽤户体验好(不需要刷新⻚⾯就可以更新数据)
  • 减轻服务端和带宽的负担

缺点:搜索引擎的⽀持度不够,因为数据都不在⻚⾯上,搜索引擎搜索不到

创建对象

使用AJAX 我们要创建XMLHttpResquest对象
var xhr = new XMLHttpResquest()

  • 对象方法
    在这里插入图片描述
  • 对象属性
    在这里插入图片描述

发送请求

open和send方法

  • open(method , url , async)
  1. method : GET和OOST
  2. url :文件在服务器上的位置
  3. async : true false true是异步 false是同步
  • send(string)
    string只能是POST请求

如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader()来添加 HTTP 头。然后在 send()方法中规定你希望发送的数据。
用 setHttpHeader(header, value)
header 头名
value 头值

xmlhttp.open("POST", "ajax-test.asp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname = Bill & lname = Gates");

原生写请求方法

  • GET方法
function getAjax() {
	var xhr = new XMLHttpResquest();
	xhr.open('GET' , 'https://music.benwebsite.cloud/banner?type=2' , true); //url是后端给的
	xhr.send();
	console.log(xhr);
}
  • POST方法
function getAjax() {
	var xhr = new XMLHttpRequest();
	xhr.open('POST' , 'https://music.benwebsite.cloud/banner' , true);
	xhr.requestHeader('content-type' , 'application/json'); //设置请求头 键值对形式 
	var sendData = {type : 2}; // 参数
	xhr.send(JSON.stringify(sendData));
	console.log(xhr);
}

jQuery写请求方法

  • GET方法
function getAjax() {
	$.ajax({
		type: GET,
		url:  https://music.benwebsite.cloud/banner,
		data: {
			type: 2
		},
		dataType: JSON,
		async: true,
		success: function(data) {
			if(data.code == 200) {
			console.log('成功');
			console.log(data);
			}else{
			console.log('错误');
			}
		}
		error: function() {
		}
})
}
  • POST方法
function getAjax() {
$.ajax({
	type: 'POST',
	url: 'https://music.benwebsite.cloud/banner',
	data: {
		type: 2
	},
	dataType: JSON,
	async: true,
	success: function(data) {
		if(data.code == 200) {
			console.log('成功');
			console.log(data);
		}else{
			console.log('错误');
		}
	}
	error: function() {
	}
})
}
举报

相关推荐

0 条评论