分享web开发知识

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

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

Ajax的使用方法

发布时间:2023-09-06 02:16责任编辑:胡小海关键词:Ajax

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

Ajax的使用方法

原文地址:https://www.cnblogs.com/hunterxing/p/9720037.html

知识推荐

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