分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

ajax请求方法

发布时间:2023-09-06 01:58责任编辑:赖小花关键词:暂无标签

ajax请求:

1、这里介绍下原生方法:

get方法: ???function getMethod(){ ???????var xhr = new XMLHttpRequest(); ???????xhr.onreadystatechange = function(){ ???????????if(xhr.readystate == 4){ ???????????????if((xhr.status >=200)&&(xhr.status < 300) || xhr.status == 304){ ???????????????????console.log(responseText); ???????????????} else { ???????????????????console.log(‘request was unsuccessful: ‘+ xhr.status); ???????????????} ???????????} ???????}; ???????xhr.open(‘get‘,‘test.php‘,false); ???????xhr.send(null); ???}post方法: ???function postMethod(){ ???????var xhr = new XMLHttpRequest(); ???????xhr.onreadystatechange = function(){ ???????????if(xhr.readystate == 4){ ???????????????if((xhr.status == 200)&&(xhr.status < 300)||(xhr.status == 304)){ ???????????????????console.log(responseText); ???????????????} else { ???????????????????console.log(‘request was unsuccessful: ‘+ xhr.status); ???????????????} ???????????} ???????}; ???????xhr.open(‘post‘,‘test.php‘,true); ???????xhr.send([text]); // text可有可无 ???} ???

open(‘method‘,url,boolean);
  method方法常见为两种:get 和 post,两者区别这里不再讲述;
  url:请求的路径
  boolean:布尔值,false为同步请求,此时js代码会等待服务器响应之后再继续执行;true为异步请求,js继续执行而不必等待响应;

xhr对象的readystate属性,检测当前活动阶段,readystate有4个取值:
  0:未初始化,尚未调用open方法;
  1:启动,已调用open方法,但尚未调用send方法;
  2:发送,已调用send方法,但尚未接收到响应;
  3:接收,已经接收到部分响应数据;
  4:完成,已经接收到全部响应数据,且可以在客户端使用了;


xhr的其它常用属性:
  responseText: 作为响应主体被返回的文本;
  status:响应的http状态
  statusText: Http状态的说明
  responseXML:若响应的内容类型是‘text/xml’或‘application/xml’,这个属性中将保存包含着响应数据的xml dom文档;

2、jquery中方法

 ??第一种写法: $.ajax({ ???????????????????type: ‘post‘, ???????????????????dataType: ‘json‘, ???????????????????url: ‘‘, ???????????????????data: { ???????????????????}, ???????????????????success: function(){}, ???????????????????error: function(){} ??????????????});
???第二种写法:$.ajax({ ???????????????????type: ‘post‘, ???????????????????dataType: ‘json‘, ???????????????????url: ‘‘, ???????????????????data: {}, ???????????????????async: false ???????????????}).done(function(resp){ ???????????????????????????????????console.log(resp); ???????????????// 相当于第一种的success ???????????????????????????????}).fail(function(){ ???????????????????????????????//相当于第一种的error ???????????????});
???第三种写法: ???????$.ajax({ ???????????type: ‘post‘, ???????????dataType: ‘json‘, ???????????data: {}, ???????????url: ‘‘, ???????????async: false // 默认是true,异步 ???????}).then(function(resolve,reject){ ???????// then 方法组合了done和fail方法; ???????}); ???????

以上后两种jQuery的ajax方法,对jQuery版本有要求,具体可参考jQuery官网

ajax请求方法

原文地址:https://www.cnblogs.com/wuting/p/9145845.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved