陆窗体的HTML就不复述了,就是用的AdminLTE的HTML, 主要是简单的AJAX请求,Session和PHP后端返回,公司的接口有俩。一个是LDAP验证用户和密码是否正确,还有一个接口是通过用户名返回用户的详细信息,因为只是内部使用,很简单的验证,没有设计token之类的,但是设计到同一html两次AJAX请求,大概的流程是:
登陆页面login.html->发送请求给check_user.php,返回flag和存储session -> login.html ajax请求得到用户详细信息
login.html Jquery
//通过用户名获取用户详细信息
$.ajax({
url: 'url',
contentType: 'application/x-www-form-urlencoded', // 如果是post必须定义
async: false, //双ajax请求必须设成false
type: 'post',
data: {'UserID': name},
beforeSend:function (){
Pace.restart(); //用的AdminLTE中的进度条插件
},
dataType: 'html',
success: function (html) {
var quickExpr=/<.+?>[^<>]*?/gi;
var EEE_Name=String(html.match(/<name>(.*?)<\/name>/g)); //因为返回的是一个不标准xml,所以直接去抓的<name>标签
var EEE_Name_detail=EEE_Name.replace(quickExpr, "");
sessionStorage.usenameName=EEE_Name_detail;
}
});
//通过用户名和密码发送给LADP服务器验证
$.ajax({
url: '../json/login_adid_check.php',
contentType: "application/x-www-form-urlencoded", // 如果是post必须定义
type: 'post',
data: {'name': name, 'pwd': pwd, 'type': type, 'domin': domin},
dataType: 'json',
success: function (data) {
if (data.flag==1) {
sessionStorage.usenameID=data.usename;
location.href='../index.html';
}
},
error: function () {
modal_js.fail({ //这里用的modal.js小插件。。可以快速建立一个modal小窗口返回信息
'msg': 'Pls recheck your userName and Password"',
'icon': 2
});
}
});login_adid_check.php
<?php
header("content-type:application/json;charset=UTF-8"); //必须
$data=$_POST;
$flag=0;
if ($data['type']=='adid') {
// connect to AD server
$ldapconn=ldap_connect("LDAP服务器") or die("Could not connect to AD server."); //连接ad服务
$set=ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); //设置参数,这个目前还不了解。
$name_1=$data['domin'] . "\\" . $data["name"];
$name=$name_1 ? $name_1 : ""; //接受需要认证的用户名和密码
$password=$data["pwd"] ? $data["pwd"] : "";
//验证用户名和密码。
$bd=ldap_bind($ldapconn, $name, $password);
$respose=[
'flag'=> $bd,
'usename'=> $data["name"],
];
echo json_encode($respose);
ldap_close($ldapconn);
};
?>附带一个index.html上的按钮可以识别回车键
人已经过原 Danny Markov 授权翻译
在本教程中,我们将学习如何使用 JS 进行AJAX调用。
术语AJAX 表示 异步的 JavaScript 和 XML。
AJAX 在 JS 中用于发出异步网络请求来获取资源。当然,不像名称所暗示的那样,资源并不局限于XML,还用于获取JSON、HTML或纯文本等资源。
有多种方法可以发出网络请求并从服务器获取数据。我们将一一介绍。
XMLHttpRequest对象(简称XHR)在较早的时候用于从服务器异步检索数据。
之所以使用XML,是因为它首先用于检索XML数据。现在,它也可以用来检索JSON, HTML或纯文本。
function success() {
var data = JSON.parse(this.responseText)
console.log(data)
}
function error (err) {
console.log('Error Occurred:', err)
}
var xhr = new XMLHttpRequest()
xhr.onload = success
xhr.onerror = error
xhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1")
xhr.send()
我们看到,要发出一个简单的GET请求,需要两个侦听器来处理请求的成功和失败。我们还需要调用open()和send()方法。来自服务器的响应存储在responseText变量中,该变量使用JSON.parse()转换为JavaScript 对象。
function success() {
var data = JSON.parse(this.responseText);
console.log(data);
}
function error(err) {
console.log('Error Occurred :', err);
}
var xhr = new XMLHttpRequest();
xhr.onload = success;
xhr.onerror = error;
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.send(JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
);
我们看到POST请求类似于GET请求。我们需要另外使用setRequestHeader设置请求标头“Content-Type” ,并使用send方法中的JSON.stringify将JSON正文作为字符串发送。
早期的开发人员,已经使用了好多年的 XMLHttpRequest来请求数据了。现代的fetch API允许我们发出类似于XMLHttpRequest(XHR)的网络请求。主要区别在于fetch()API使用Promises,它使 API更简单,更简洁,避免了回调地狱。
Fetch 是一个用于进行AJAX调用的原生 JavaScript API,它得到了大多数浏览器的支持,现在得到了广泛的应用。
fetch(url, options)
.then(response => {
// handle response data
})
.catch(err => {
// handle errors
});
API参数
fetch() API有两个参数
API返回Promise对象
fetch() API返回一个promise对象。
错误处理
请注意,对于成功的响应,我们期望状态代码为200(正常状态),但是即使响应带有错误状态代码(例如404(未找到资源)和500(内部服务器错误)),fetch() API 的状态也是 resolved,我们需要在.then() 块中显式地处理那些。
我们可以在response 对象中看到HTTP状态:
const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.catch(err => console.error(err));
getTodoItem.then(response => console.log(response));
Response
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
在上面的代码中需要注意两件事:
错误处理
我们来看看当HTTP GET请求抛出500错误时会发生什么:
fetch('http://httpstat.us/500') // this API throw 500 error
.then(response => () => {
console.log("Inside first then block");
return response.json();
})
.then(json => console.log("Inside second then block", json))
.catch(err => console.error("Inside catch block:", err));
Inside first then block
? ? Inside catch block: SyntaxError: Unexpected token I in JSON at position 4
我们看到,即使API抛出500错误,它仍然会首先进入then()块,在该块中它无法解析错误JSON并抛出catch()块捕获的错误。
这意味着如果我们使用fetch()API,则需要像这样显式地处理此类错误:-
fetch('http://httpstat.us/500')
.then(handleErrors)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error("Inside catch block:", err));
function handleErrors(response) {
if (!response.ok) { // throw error based on custom conditions on response
throw Error(response.statusText);
}
return response;
}
? Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)
fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
body: JSON.stringify({
completed: true,
title: 'new todo item',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err))
Response
? {completed: true, title: "new todo item", userId: 1, id: 201}
在上面的代码中需要注意两件事:-
Axios API非常类似于fetch API,只是做了一些改进。我个人更喜欢使用Axios API而不是fetch() API,原因如下:
// 在chrome控制台中引入脚本的方法
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://unpkg.com/axios/dist/axios.min.js';
document.head.appendChild(script);
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => console.log(response.data))
.catch(err => console.error(err));
Response
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
我们可以看到,我们直接使用response获得响应数据。数据没有任何解析对象,不像fetch() API。
错误处理
axios.get('http://httpstat.us/500')
.then(response => console.log(response.data))
.catch(err => console.error("Inside catch block:", err));
Inside catch block: Error: Network Error
我们看到,500错误也被catch()块捕获,不像fetch() API,我们必须显式处理它们。
axios.post('https://jsonplaceholder.typicode.com/todos', {
completed: true,
title: 'new todo item',
userId: 1
})
.then(response => console.log(response.data))
.catch(err => console.log(err))
{completed: true, title: "new todo item", userId: 1, id: 201}
我们看到POST方法非常简短,可以直接传递请求主体参数,这与fetch()API不同。
作者:Danny Markov 译者:前端小智 来源:tutorialzine
原文:https://tutorialzine.com/2017/12-terminal-commands-every-web-developer-should-know
现代web开发中,表单是用户与网站互动的重要方式之一。HTML5为表单提交提供了强大的功能和丰富的输入类型,让收集和验证用户输入数据变得更加容易和安全。本文将详细介绍HTML5表单的各个方面,包括基本结构、输入类型、验证方法和提交过程。
HTML表单由<form>标签定义,它可以包含输入字段、标签、按钮等元素。一个基本的表单结构如下所示:
<form action="/submit_form" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
<label for="email">电子邮箱:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="提交">
</form>
在这个例子中,表单有两个输入字段:姓名和电子邮箱。每个输入字段都有一个<label>标签,这不仅有助于用户理解输入的内容,也有助于屏幕阅读器等辅助技术。<form>标签的action属性定义了数据提交到服务器的URL,method属性定义了提交数据的HTTP方法(通常是post或get)。
HTML5提供了多种输入类型,以支持不同的数据格式和设备。
<!-- 单行文本 -->
<input type="text" name="username" placeholder="请输入用户名" required>
<!-- 密码 -->
<input type="password" name="password" required minlength="8">
<!-- 邮箱 -->
<input type="email" name="email" required placeholder="example@domain.com">
<!-- 搜索框 -->
<input type="search" name="search" placeholder="搜索...">
<!-- 数值 -->
<input type="number" name="age" min="18" max="100" step="1" required>
<!-- 滑动条 -->
<input type="range" name="volume" min="0" max="100" step="1">
<!-- 电话号码 -->
<input type="tel" name="phone" pattern="^\+?\d{0,13}" placeholder="+8613800000000">
<!-- 日期 -->
<input type="date" name="birthdate" required>
<!-- 时间 -->
<input type="time" name="appointmenttime">
<!-- 日期和时间 -->
<input type="datetime-local" name="appointmentdatetime">
<!-- 复选框 -->
<label><input type="checkbox" name="interest" value="coding"> 编程</label>
<label><input type="checkbox" name="interest" value="music"> 音乐</label>
<!-- 单选按钮 -->
<label><input type="radio" name="gender" value="male" required> 男性</label>
<label><input type="radio" name="gender" value="female"> 女性</label>
<!-- 下拉选择 -->
<select name="country" required>
<option value="china">中国</option>
<option value="usa">美国</option>
</select>
<!-- 颜色选择器 -->
<input type="color" name="favcolor" value="#ff0000">
<!-- 文件上传 -->
<input type="file" name="resume" accept=".pdf,.docx" multiple>
HTML5表单提供了内置的验证功能,可以在数据提交到服务器之前进行检查。
<input type="text" name="username" required>
<input type="text" name="zipcode" pattern="\d{5}(-\d{4})?" title="请输入5位数的邮政编码">
<input type="number" name="age" min="18" max="99">
<input type="text" name="username" minlength="4" maxlength="8">
当用户填写完表单并点击提交按钮时,浏览器会自动检查所有输入字段的有效性。如果所有字段都满足要求,表单数据将被发送到服务器。否则,浏览器会显示错误信息,并阻止表单提交。
<input type="submit" value="提交">
可以使用JavaScript来自定义验证或处理提交事件:
document.querySelector('form').addEventListener('submit', function(event) {
// 检查表单数据
if (!this.checkValidity()) {
event.preventDefault(); // 阻止表单提交
// 自定义错误处理
}
// 可以在这里添加额外的逻辑,比如发送数据到服务器的Ajax请求
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单提交并显示JSON</title>
</head>
<body>
<!-- 表单定义 -->
<form id="myForm">
<label for="name">姓名:</label>
<input type="text" id="name" name="name">
<br>
<label for="email">电子邮件:</label>
<input type="email" id="email" name="email">
<br>
<input type="button" value="提交" onclick="submitForm()">
</form>
<script>
// JavaScript函数,处理表单提交
function submitForm() {
// 获取表单元素
var form=document.getElementById('myForm');
// 创建一个FormData对象
var formData=new FormData(form);
// 创建一个空对象来存储表单数据
var formObject={};
// 将FormData转换为普通对象
formData.forEach(function(value, key){
formObject[key]=value;
});
// 将对象转换为JSON字符串
var jsonString=JSON.stringify(formObject);
// 弹出包含JSON字符串的对话框
alert(jsonString);
// 阻止表单的默认提交行为
return false;
}
</script>
</body>
</html>
在这个例子中:
注意,这个例子中我们使用了type="button"而不是type="submit",因为我们不希望表单有默认的提交行为。我们的JavaScript函数submitForm会处理所有的逻辑,并且通过返回false来阻止默认的表单提交。如果你想要使用type="submit",你需要在<form>标签上添加一个onsubmit="return submitForm()"属性来代替按钮上的onclick事件。
HTML5的表单功能为开发者提供了强大的工具,以便创建功能丰富、用户友好且安全的网站。通过使用HTML5的输入类型和验证方法,可以确保用户输入的数据是有效的,同时提高用户体验。随着技术的不断进步,HTML5表单和相关API将继续发展,为前端工程师提供更多的可能性。
*请认真填写需求信息,我们会在24小时内与您取得联系。