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的更多相关文章

  1. content-type常见类型辨析(以ajax与springmvc前后端交互为例)

    博客搬家: content-type常见类型辨析(以ajax与springmvc前后端交互为例) 在http报文的首部中,有一个字段Content-type,表示请求体(entity body)中的数 ...

  2. SSM-网站后台管理系统制作(4)---Ajax前后端交互

    前提:Ajax本身就为前后端交互服务的,实现功能:用户输入信息,实时判断用户的情况,这也是现在登录界面普遍流行的做法.前端js通过注释识别Controller层,该层查询返回,和之前Google验证码 ...

  3. thinkphp+jquery+ajax前后端交互注册验证

    thinkphp+jquery+ajax前后端交互注册验证,界面如下 register.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. ...

  4. Vue-CLI项目-axios模块前后端交互(类似ajax提交)

    08.31自我总结 Vue-CLI项目-axios前后端交互 一.模块的安装 npm install axios --save #--save可以不用写 二.配置main.js import axio ...

  5. 从MVC到Ajax再到前后端分离的思考

    前言 一位小妹去面试前端,前端leader问了"什么是ajax?",答:"接收后台的数据,然后然后自己填充和渲染样式":一位小哥去面试后台,技术经理问了&quo ...

  6. 前后端交互实现(nginx,json,以及datatable的问题相关)

    1.同源问题解决 首先,在同一个域下搭建网络域名访问,需要nginx软件,下载之后修改部分配置 然后再终端下cmd  nginx.exe命令,或者打开nginx.exe文件,会运行nginx一闪而过, ...

  7. Node之简单的前后端交互

    node是前端必学的一门技能,我们都知道node是用的js做后端,在学习node之前我们有必要明白node是如何实现前后端交互的. 这里写了一个简单的通过原生ajax与node实现的一个交互,刚刚学n ...

  8. Django之META与前后端交互

    Django之META与前后端交互 1 提交表单之GET 前端提交数据与发送 1)提交表单数据 2)提交JSON数据 后端的数据接收与响应 1)接收GET请求数据 2)接收POST请求数据 3)响应请 ...

  9. 百度ueditor的图片上传,前后端交互使用

    百度ueditor的使用 一个文本编辑器,看了网上很多文档写的很乱,这里拾人牙慧,整理下怎么使用. 这个东西如果不涉及到图片附件上传,其实很简单,就是几个前端文件,直接引用,然后配置下ueditor. ...

随机推荐

  1. kentico11 教程,

    create master page with css list menu Add the navigation menu Add a dynamic web part that will repre ...

  2. 【POJ 3263】 Tallest Cow

    [题目链接] http://poj.org/problem?id=3263 [算法] 若A和B两头牛可以互相看见,那么说明中间的牛的高度都至少比它们少1,因此,我们可以引入一个差分数组c 对于每组关系 ...

  3. P3178 [HAOI2015]树上操作 树链剖分

    这个题就是一道树链剖分的裸题,但是需要有一个魔性操作___编号数组需要开longlong!!!震惊!真的神奇. 题干: 题目描述 有一棵点数为 N 的树,以点 为根,且树点有边权.然后有 M 个操作, ...

  4. springmvc的jar包

     <!-- spring框架的的组件构成(springFramework)--> 一.核心部分Core Container 1.1 spring-core,spring-beans 提供控 ...

  5. Systick 更新

    之前写的systick_config(loadvalue) 根据系统时钟为72Mhz来写的,如果system clock不是72MHz怎么办? 重新写了一下,先获取,系统时钟频率. //参数为ms v ...

  6. Scala 获取当前时间

    def NowDate(): String = { val now: Date = new Date() val dateFormat: SimpleDateFormat = new SimpleDa ...

  7. IBatis异常: Cannot find class: VARCHAR

    今天再项目里添加新功能时,突然爆出 org.springframework.beans.factory.BeanCreationException: Error creating bean with ...

  8. Effective C++ 深入理解inline

    Effective C++ 深入理解inline inline语义 inline本义是将所调用函数用自身的函数本体替换之,免受函数调用所招致的额外开销,比宏还要不易出错:但是实际上inline的受编译 ...

  9. 【转】Linux账号管理之useradd

    转自:http://www.jb51.net/article/45848.htm Linux 系统是一个多用户多任务的分时操作系统,任何一个要使用系统资源的用户,都必须首先向系统管理员申请一个账号,然 ...

  10. jsp中session执行机制