ajax学习----json,前后端交互,ajax
json


<script>
var obj = {"name": "xiaopo","age": 18,"gender": "girl"};
console.log(obj);
console.log(typeof obj);//Object(前端对象)
var obj1 = JSON.stringify(obj);//把js对象转换成json字符串
console.log(obj1);//{"name":"xiaopo","age":18,"gender":"girl"}
console.log(typeof obj1);//string //定义json字符串 直接定义 var obj2 = '{"name": "xiaopo","age": 18,"gender": "girl"}';
// var obj1 = JSON.stringify(obj);//把js对象转换成json字符串
var obj2 = '{"name": "xiaopo","age": 18,"gender": "girl"}';
console.log(obj2);//{"name":"xiaopo","age":18,"gender":"girl"}
console.log(typeof obj2);//string var obj3 = JSON.parse(obj2);//把json字符串转换成js对象
console.log(obj3);
console.log(typeof obj3);//Object
</script>

前后端交互
服务端代码
#! /usr/bin/env python3
# -*- coding: utf-8 -*- import tornado.ioloop
import tornado.web
import tornado.httpserver
from tornado.options import define, options
import os
import random define('port', default=9000, help='run port', type=int) # 主函数
class MainHandler(tornado.web.RequestHandler)://直接输入端口访问的话
def get(self):
self.write('<h1>hello world 999</h1>')
# form 请求视图
class RegHandler(tornado.web.RequestHandler):
def get(self)://form下的get方法提交
self.write('Reg的get返回')
# # 用户名
username = self.get_argument('username')
# # 密码
password = self.get_argument('password')
print('用户名', username, '密码', password) def post(self):
# 用户名//form下的post提交(按钮提交)
username = self.get_argument('username')
# 密码
password = self.get_argument('password')
# 性别
gender = self.get_argument('gender')
# 爱好
hobby = self.get_arguments('hobby')
# 地址
address = self.get_arguments('address')
# 个人简介
personal = self.get_argument('personal')
print('用户名', username, '密码', password)
print('性别', gender, '爱好', hobby)
print('地址', address, '个人简介', personal) # Ajax 请求视图
class AjaxHandler(tornado.web.RequestHandler):
# get 请求
def get(self):
username = self.get_argument('username')
password = self.get_argument('password')
print('method get username:{} password:{}'.format(username, password)) # post 请求
def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
# 后台逻辑判断
if username and password:
print('method post username:{} password:{}'.format(username, password))
else:
# 如果没有用户名和密码 就返回提示消息
self.write('用户名或密码不能为空') # 数据视图
class DataHandler(tornado.web.RequestHandler):
def get(self):
articles = []
for i in range(3):
article = {}
article['title'] = 'title' + str(random.randint(100, 1000))
articles.append(article)
# print(articles)
self.write({'articles': articles}) application = tornado.web.Application(
handlers=[
(r'/', MainHandler),
# reg 路由
(r'/reg', RegHandler),
# ajax 路由
(r'/ajax', AjaxHandler),
# 返回数据的路由
(r'/data', DataHandler),
],
# 设置静态路径
static_path= os.path.join(os.path.dirname(__file__), "static"),
# 设置模板文件
# template_path = os.path.join(os.path.dirname(__file__), "template"),
# 开启debug模式
debug=True
) if __name__ == "__main__":
tornado.options.parse_command_line()
print('端口是', options.port)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
form表单代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>form</title>
<style>
.form {
width: 400px;
margin: 20px auto;
} .form-item {
margin-top: 20px;
} label.label-item {
display: inline-block;
width: 100px;
text-align: right;
} input[type='radio'], input[type='checkbox'] {
vertical-align: -2px;
} textarea[name="personal"] {
vertical-align: top;
}
</style>
</head>
<body>
<!--
form两个很重要的属性 name 后台根据name拿值
value 用户输入的值
reg?
user=sdsdsdsd&
password=sdsddsdd&
address=0&
personal=
-->
<form action="/reg" class="form" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="username" class="label-item">用户名:</label>
<input type="text" name="username" placeholder="请输入用户名" id="username">
</div>
<div class="form-item">
<label for="password" class="label-item">密码:</label>
<input type="password" name="password" placeholder="请输入密码" id="password">
</div>
<div class="form-item">
<label class="label-item">性别:</label>
<label for="male">男</label>
<input type="radio" name="gender" value="male" id="male">
<label for="female">女</label>
<input type="radio" name="gender" value="female" id="female">
<label for="secret">保密</label>
<input type="radio" name="gender" value="secret" id="secret">
</div>
<div class="form-item">
<label class="label-item">爱好:</label>
<label for="coding">coding</label>
<input type="checkbox" name="hobby" value="code" id="coding">
<label for="read">阅读</label>
<input type="checkbox" name="hobby" value="read" id="read">
<label for="game">游戏</label>
<input type="checkbox" name="hobby" value="game" id="game">
<label for="sleep">睡觉</label>
<input type="checkbox" name="hobby" value="sleep" id="sleep">
</div>
<div class="form-item">
<label for="address" class="label-item">地址:</label>
<select name="address" id="address">
<option value="0">--请选择--</option>
<option value="1">北京</option>
<option value="2">深圳</option>
<option value="3">杭州</option>
<option value="4">长沙</option>
</select>
</div>
<div class="form-item">
<label for="personal" class="label-item">个人简介:</label>
<textarea name="personal" id="personal" style="resize: none;"></textarea>
</div>
<div class="form-item">
<input type="submit" value="提交" class="btn btn-success">
<input type="reset" value="重置" class="btn btn-warning">
</div>
</form>
</body>
</html>
服务器运行的前提下

当点击提交按钮,(post方式), 信息就已经上传到服务器

如果在form.html中将method改成"get", 那么在服务器中的get方法是

点击提交以后页面会返回

那么服务器控制台的输出就是

需要注意的是:
form.html中的
指向的是服务端的
后面再来介绍ajax的提交方法
ajax
全称ansync JavaScript and XML,是有一门异步的加载技术,局部刷新
ajax的操作有两种,一种是原生的,一种是jq(主要学习jq的)
异步加载,可以在不重载整个页面的前提下,实现局部刷新
原生ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="btn">提交</button>
<script>
var btn = document.getElementById("btn");
btn.onclick = function () {
//创建对象
var xhr = new XMLHttpRequest();
//method url async(要不要异步加载)
// xhr.open("get","/ajax?username=xiaopo&password=999",true);
xhr.open("post","/ajax",true);
//post请求 设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //发送请求
xhr.send("username=xiaopo&password=999");
// xhr.send();
xhr.onreadystatechange = function () {
//readyState 有5个值
//0 没有启动
// 1 初始化 open之前
// 2 发送请求 send之后
// 3 响应 有一部分数据接收
// 4 数据全部接收
if(xhr.readyState === 4){
if(xhr.status === 200){
alert(xhr.status);//http 状态码
}else{
alert(xhr.statusText);
}
}
}
}
</script>
</body>
</html>
运行服务端,加载页面
点击提交
服务器返回
信息来源于原生ajax中的
jq下的ajax
$.ajax() 表示创建了一个ajax对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p><input type="text" id="username" placeholder="请输入你的账号"></p>
<p><input type="password" id="password" placeholder="请输入你的密码"></p>
<p id="wrap" style="color: red;"></p>
<button id="btn">按钮</button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
//ajax 必须在服务器的环境下才有效果 不能跨域
var $btn = $("#btn");
$btn.click(function () {
$.ajax({
"method": "post",
"url": "/ajax",
"data": {
// value 是 js jq val() js对象和jq对象
username: $("#username").val(),
password: $("#password").val()
},
"success": function (data) {
console.log("success");
console.log(data);
$("#wrap").html(data);
},
"error": function (error) {
console.log("error");
console.log(error.readyState);
console.log(error.statusText);
}
});
}); // $.ajax({
//
// }) /*$.get({ });*/ $.post({ })
</script>
</body>
</html>

点击提交
当信息不全时,返回
ajax学习----json,前后端交互,ajax的更多相关文章
- content-type常见类型辨析(以ajax与springmvc前后端交互为例)
博客搬家: content-type常见类型辨析(以ajax与springmvc前后端交互为例) 在http报文的首部中,有一个字段Content-type,表示请求体(entity body)中的数 ...
- SSM-网站后台管理系统制作(4)---Ajax前后端交互
前提:Ajax本身就为前后端交互服务的,实现功能:用户输入信息,实时判断用户的情况,这也是现在登录界面普遍流行的做法.前端js通过注释识别Controller层,该层查询返回,和之前Google验证码 ...
- thinkphp+jquery+ajax前后端交互注册验证
thinkphp+jquery+ajax前后端交互注册验证,界面如下 register.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. ...
- Vue-CLI项目-axios模块前后端交互(类似ajax提交)
08.31自我总结 Vue-CLI项目-axios前后端交互 一.模块的安装 npm install axios --save #--save可以不用写 二.配置main.js import axio ...
- 从MVC到Ajax再到前后端分离的思考
前言 一位小妹去面试前端,前端leader问了"什么是ajax?",答:"接收后台的数据,然后然后自己填充和渲染样式":一位小哥去面试后台,技术经理问了&quo ...
- 前后端交互实现(nginx,json,以及datatable的问题相关)
1.同源问题解决 首先,在同一个域下搭建网络域名访问,需要nginx软件,下载之后修改部分配置 然后再终端下cmd nginx.exe命令,或者打开nginx.exe文件,会运行nginx一闪而过, ...
- Node之简单的前后端交互
node是前端必学的一门技能,我们都知道node是用的js做后端,在学习node之前我们有必要明白node是如何实现前后端交互的. 这里写了一个简单的通过原生ajax与node实现的一个交互,刚刚学n ...
- Django之META与前后端交互
Django之META与前后端交互 1 提交表单之GET 前端提交数据与发送 1)提交表单数据 2)提交JSON数据 后端的数据接收与响应 1)接收GET请求数据 2)接收POST请求数据 3)响应请 ...
- 百度ueditor的图片上传,前后端交互使用
百度ueditor的使用 一个文本编辑器,看了网上很多文档写的很乱,这里拾人牙慧,整理下怎么使用. 这个东西如果不涉及到图片附件上传,其实很简单,就是几个前端文件,直接引用,然后配置下ueditor. ...
随机推荐
- [Codeforces Round472C] Three-level Laser
[题目链接] https://codeforces.com/contest/957/problem/C [算法] 二分 注意精度问题 时间复杂度 :O(NlogN) [代码] #include< ...
- P3202 [HNOI2009]通往城堡之路 神仙题
这个题不是坑人吗...写个tarjan标签,然后拿这么个神仙题来搞...代码有点看不懂,有兴趣的可以去洛谷题解区看看,懒得想了. 题干: 题目描述 听说公主被关押在城堡里,彭大侠下定决心:不管一路上有 ...
- P1402 酒店之王 网络流
大水题,我自己瞎做就做出来了,没啥说的,zz建图,就是板子. 题干: 题目描述 XX酒店的老板想成为酒店之王,本着这种希望,第一步要将酒店变得人性化.由于很多来住店的旅客有自己喜好的房间色调.阳光等, ...
- LuoguP4462 [CQOI2018]异或序列
https://zybuluo.com/ysner/note/1124952 题面 给你一个大小为\(n\)的序列,然后给你一个数字\(k\),再给出\(m\)组询问,询问给出一个区间,问这个区间里面 ...
- thinkphp关联操作
比如:你要求删除用户的时候,同时删除与用户有关的所有信息. 一对一: 有 (HAS_ONE) 属于 (BELONGS_TO) 一对多: 有 (HAS_MANY) 属于 (BELONG_ ...
- Gym - 101972B Arabella Collegiate Programming Contest (2018) B. Updating the Tree 树DFS
题面 题意:T组数据,每次给你1e5个点的树(1为根),每个点有一权值,询问1-n每个节点的子树中, 至少修改几个点的权值(每次都可以任意修改),才能让子树中任意2点的距离==他们权值差的绝对值 无解 ...
- Windows虚拟机中无法传输Arduino程序的问题
现象 最近儿子在学习机器人编程,其中有一步需要把板子和电脑用USB线相连接,然后把在电脑中编辑好的程序传输到Arduino板子上.在Windows笔记本上能正常工作,但在我的Mac笔记本的Window ...
- 数据库部署到linux服务器,供本地访问。
1. 将本地的sql文件上传至服务器 scp /Users/fangke/Documents/article.sql root@IP:/usr/local 2. 登陆服务器的mysql 3. 创建数 ...
- Idea使用Maven搭建SpringMVC的HelloSpringMvc并配置插件Maven和Jetty
这篇博文只是纯粹的搭建一个SpringMVC的项目, 并不会涉及里面配置文件该写些什么. 只是纯粹的搭建一个初始的Hello SpringMVC的项目. 废话不多说,上图. 1. 打开IDEA 并且 ...
- Laravel 5.4.36 session 发现
由于Laravel session机制完全脱离了PHP自带的session机制 因此对于php.ini 配置session对Laravel 是不会产生影响 代码路径: vendor/larav ...
