网站首页 > 技术文章 正文
什么是ajax?
ajax就是一个异步的javascript和xml,你可以不要太在意书面上的意思,你要知道,我们向后台请求数据,除了基本的form表单外,大多数情况下我们是使用的ajax向后台发送请求,ajax比form表单的功能更强大!
ajax基本格式
var xhr = new XMLHttpRequest();
xhr.open(请求方多,请求地址,是否异步); // 请求方式,请求地址,是否异步
xhr.setRequestHeader("Content-type","application/json"); // 设置请求头
xhr.onreadystatechange = function(e)
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var info = xhr.responseText; // 返回的数据
}
}
var data = {"info":"zsf"}; // 发送给后台的数据
xhr.send(JSON.stringify(data));
ajax发送json数据
index.html
<html>
<head>
<title>js</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div>
我是显示内容
</div>
<div>
<button class="ajax_btn">原生ajax</button>
</div>
</body>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="./index.js">
</script>
</html>
index.js
$(function(){
$(".ajax_btn").click(function(){
var xhr = new XMLHttpRequest();
xhr.open("post","http://localhost",true);
xhr.setRequestHeader("Content-type","application/json");
xhr.onreadystatechange = function(e)
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var info = xhr.responseText;
console.log(JSON.parse(info));
}
}
var data = {"info":"zsf"};
xhr.send(JSON.stringify(data));
});
})
index.php
<?php
header("Access-Control-Allow-Origin:*");
$info = file_get_contents('php://input'); // 改成这样可以获取到原生发送的application/json
$info = json_decode($info,true);
$info['age'] = 18;
print_r(json_encode($info));
?>
注:
xhr.setRequestHeader("Content-type","application/json"):说明我们发送json字符串到后台,所以,使用JSON.stringfy进行转换json字符串。
header("Access-Control-Allow-Origin:*"):这里是会涉及到跨域相关;
file_get_contents('php://input'):获取发过来的json串,json_decode转换成php的数组,记住后面的那个 true 值。print_r在php后台进行输出,就会返回到ajax的onreadystatechange回调函数中。
猜你喜欢
- 2024-10-03 Spring Boot API 如何获得 JSON 数据
- 2024-10-03 大白话 golang 教程-20-使用 RPC 远程调用
- 2024-10-03 软件更新速递:Go发布1.15版本,这些新特性抢先看
- 2024-10-03 掌握 Postman 工具发送请求的简易教程
- 2024-10-03 python接口自动化-Json数据处理(python接口自动化流程)
- 2024-10-03 python接口自动化(八)--发送post请求的接口(详解)
- 2024-10-03 Flink 在唯品会的实践(唯品会 分析)
- 2024-10-03 Java POST JSON 数据处理异常 (code 160)): was expecting double-quote
- 2024-10-03 使用Postman发送POST请求的指南(postman如何发送post请求)
- 2024-10-03 在Postman脚本中发送请求(pm.sendRequst)
- 02-21走进git时代, 你该怎么玩?_gits
- 02-21GitHub是什么?它可不仅仅是云中的Git版本控制器
- 02-21Git常用操作总结_git基本用法
- 02-21为什么互联网巨头使用Git而放弃SVN?(含核心命令与原理)
- 02-21Git 高级用法,喜欢就拿去用_git基本用法
- 02-21Git常用命令和Git团队使用规范指南
- 02-21总结几个常用的Git命令的使用方法
- 02-21Git工作原理和常用指令_git原理详解
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)