| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <script src="js/jquery-2.1.4.js"></script>
- </head>
- <body>
- <form action="#" >
- 账号: <input type="text" name="username" id="username"><br>
- 密码: <input type="password" name="password" id="password"><br>
- <input type="button" value="登录" onclick="get()">
- </form>
- <button onclick="get()">get</button>
- <button onclick="post()">post</button>
- <button onclick="ajax()">ajax</button>
- </body>
- <script>
- function ajax(){
- /**
- * 在jquery 用的更多是另外ajax 方法
- * $.ajax({
- * url: 请求路径,
- * data: 请求参数
- * type: 请求方式
- * contentType: 请求数据格式,
- * dataType: 响应数据格式
- * success: 成功回调函数
- * error: 失败的回调函数
- * })
- */
- var username = document.getElementById("username").value
- var password = document.getElementById("password").value
- var obj = {"username":username,"password":password}
- $.ajax({
- url: "http://c46a5489.natappfree.cc/login1",
- data: JSON.stringify(obj), // 把传递js 对象参数转成json 字符串
- type: "post",
- dataType: "json", // 期望后端返回数据格式为json
- contentType:"application/json;charset=utf-8", // 前端给后端发送数据格式为json
- success: function (result) {
- if(result.success){
- alert("登录成功")
- }else{
- alert("登录失败")
- }
- }
- })
- }
- function post(){
- /**
- * 使用jquery 框架发送
- * $.post(url,请求参数,回调函数)
- */
- var username = document.getElementById("username").value
- var password = document.getElementById("password").value
- $.post("http://c46a5489.natappfree.cc/login",{username:username,password:password},function (result){
- console.log(result);
- if(result.success){
- alert("登录成功")
- }else{
- alert("登录失败")
- }
- })
- }
- function get(){
- // 使用jquery 发送异步请求
- /**
- * $: 表示jquery 对象
- * $.get() 调用jquery 的对象额函数
- * get(url: 请求路径,data: 请求参数,callback: function(result){
- * 这个回调函数当中result 就是后端给前端返回的数据
- * jquery 发送请求有一个优点, 后端如果给前端返回json 数据
- * result-> json -> js 对象 他会帮我们把json 转成js 对象
- * 回调函数, 当后端处理成功就会毁掉这个callback
- * }))
- */
- /**
- * get方法请求参数 可以直接在路径当中写
- *
- * 路劲: 协议://ip:port/请求路径?请求参数名=请求参数值&请求参数名=请求参数值
- */
- var username = document.getElementById("username").value
- var password = document.getElementById("password").value
- $.get("http://c46a5489.natappfree.cc/login",{username:username,password:password},function (result) {
- // result 后端给前端返回的数据一般是json 的数据格式
- console.log(result);
- if(result.success){
- alert("登录成功")
- }else{
- alert("登录失败")
- }
- })
- /**
- * 提供一个登录界面
- * 发送一个get 请求把账号和密码发送请求携带到后端
- *
- */
- }
- </script>
- </html>
|