ajax提交
<script>
$("#submit").on('click',function(){ //选择id为submit的按钮,点击时触发函数
$.ajax({
type: 'POST',
url: "{:url('admin/update')}",
data: $(".layui-form").serialize(), //选择class为layui-form的数据 serialize() 方法通过序列化表单值,创建 URL 编码文本字符串.
dataType: "json",
success: function(data){ //返回成功函数
console.log(data);
if (data.status == 1) {
alert(data.message);
window.location.href = "{:url('admin/index')}";
} else {
alert(data.message);
window.location.href = "{:url('admin/ediit')}";
}
}
})
})
})
</script>
<div id="file-pretty">
<input id="file_path" name="file" type="file" class="form-control" style="display:none">
<div class="input-append input-group">
<span class="input-group-btn">
<button id="btn_path" type="button" class="btn btn-white">选择图片</button>
</span>
<input id="info_path" type="text" name='img' class="form-control input-large" value="">
</div>
</div>
<script>
$(function(){
$('#btn_path').click(function(){
$("#file_path").click();//使用选择图片按钮覆盖原来的上传文件按钮,当点击选择图片时,相当于点击上传文件按钮。
});
//异步上传
//当id为file_path的元素发生变化时执行函数。delegate为绑定一个事件。
http://www.365mini.com/page/jquery-delegate.htm(delegate的用法)
http://www.w3school.com.cn/jquery/event_change.asp(change的用法)
$("body").delegate("#file_path", 'change', function(){
var filepath = $("input[name='file']").val();var arr = filepath.split('.');
var ext = arr[arr.length-1];//图片后缀
if('gif|jpg|png|bmp'.indexOf(ext)>=0){ //判断ext中是否有gif,jpg... http://www.w3school.com.cn/jsref/jsref_indexOf.asp(indexof的用法)
$.ajaxFileUpload({url: '{:url('upload_image')}',
type: 'post',
data: { name: 'file' },// 选择name为“file”的元素的数据(与上面的id选择器进行比较 data: $(".layui-form").serialize())
secureuri: false,
fileElementId: 'file_path',
dataType: 'json',
success: function (data, status) {
$('#info_path').val(data);
$('#info_path').focus(); //当元素获得焦点时,发生 focus 事件。
http://www.w3school.com.cn/jquery/event_focus.asp(focus的用法)
error: function (data, status, e){
layer.alert('上传失败');
}
});
}else{
// 清空file
$('#file_path').val('');
layer.alert('请上传合适的图片类型');
}
});
});
</script>