get 和 post 最最明显和重要的区别就是 url 上参数是否可见。
普通使用(非ajax)最普遍的就是提交from表单。
表单可以设置成是post还是get提交。
你用get提交from 表单会把表单中的参数拼接到请求url 后。而post 是在请求体里。
Jquery ajax post/get 提交方式的注意问题
1、用ajax的时候你是在地址栏虽然看不到url。但get 和 post 本质并没变。
你可以在控制台-网络处看到他发出的请求url。 (所以get还是不安全)
get:
$(function() {
$("#addok").click(function(){
var name = $("#addname").val(); // 从页面获取数据
var psw = $("#addpassword").val(); // 从页面获取数据
var type = $("#addtype").val(); // 从页面获取数据
if(name == null || name.trim() < 1){
alert("用户名为空");
}
if(psw == null || psw.trim() < 1) {
alert("密码为空");
}
var prefix = getCurrentDomain(); // 自己写的获取域名方法(别管他)
var url = prefix + "/user/add"; // 请求url
// jquery ajax get 请求
$.get(url, {username : name, password : psw, userType : type},
function(result){
if(result == 'success') {
/*window.location.reload();*/
alert("添加成功");
} else {
alert("添加失败");
}
});
});
});
后端处理时接收路径 /user/add
请求后浏览器查看能看到连接。get请求自动把参数拼接到url 上了。
可以看到浏览器地址栏并没变,(符合ajax 的情况)
post:
$(function() {
$("#addok").click(function(){
var name = $("#addname").val(); // 从页面获取数据
var psw = $("#addpassword").val(); // 从页面获取数据
var type = $("#addtype").val(); // 从页面获取数据
if(name == null || name.trim() < 1){
alert("用户名为空");
}
if(psw == null || psw.trim() < 1) {
alert("密码为空");
}
var prefix = getCurrentDomain(); // 自己写的获取域名方法(别管他)
var url = prefix + "/user/add"; // 请求url
// jquery ajax get 请求
$.post(url, {username : name, password : psw, userType : type},
function(result){
if(result == 'success') {
/*window.location.reload();*/
alert("添加成功");
} else {
alert("添加失败");
}
});
});
});
可以看到参数并没在url 上
2、用ajax 发请求可以不用from 表单包裹相应想要提交信息的代码。
比如上面的ajax 请求获取数据就是 写在一个div 里的 默认不显示,点击添加按钮时通过js 改变其属性
并让其浮出来。
<div id="add-dlg" class="alert-add" style="display: none;">
<table border="0" cellspacing="0" cellpadding="0" width="330">
<tr>
<td width="15%" height="40" style="background: #f4f4f4; text-align: right;">
<label>用户名:</label>
</td>
<td colspan="3">
<input id="addname" type="text" width="35%"/>
</td>
</tr>
<tr>
<td width="15%" height="40" style="background: #f4f4f4;text-align: right;">
<label>密码:</label>
</td>
<td colspan="3" width="35%">
<input id="addpassword" type="password"/>
</td>
</tr>
<tr>
<td width="15%" height="40" style="background: #f4f4f4;text-align: right;">
<label>类型:</label>
</td>
<td colspan="3" width="35%">
<select id="addtype" style="display: inline-block;">
<option value="0">管理员</option>
<option value="1">普通用户</option>
</select>
</td>
</tr>
</table>
<button id="addre" class="but3" type="button">重置</button>
<button id="addok" class="but2" type="button">添加</button>
</div>
3、不要手动拼接url 参数。
刚开始的时候我自己是手动拼接的url参数。
虽然能发起请求,但这样不管是get 还是post 都暴露了信息。
不要这样做
var url = prefix + "/user/add"+"?username=" + name + "&password" + psw + "userType" + type; // 请求url
// jquery ajax get 请求
$.get(url,function(result){
if(result == 'success') {
/*window.location.reload();*/
alert("添加成功");
} else {
alert("添加失败");
}
});
});