1. 程式人生 > 其它 >通過jQuery傳送ajax請求實現from表單提交上傳

通過jQuery傳送ajax請求實現from表單提交上傳

HTML程式碼如下{{--jQueryAjax提交 laravel框架簡單測試--}}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>{{--線上jQuery--}}
<title>Document</title>
</head>
<body>
{{--form表單HTML程式碼--}}
<div class="modal-body">
<form class="form-horizontal" id="addRole">
<div class="form-group">
<div class="col-sm-10">
<input type="text" class="form-control" name="ro" id="role_name" placeholder="請輸入姓名">
<input type="hidden" name="_token" value="{{csrf_token()}}">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="text" class="form-control" name="re" id="role_description" placeholder="請設定角色">
</div>
</div>
</form>
<div class="form-group">
<div>
<button type="button" id="BTN" class="btn btn-default">立即提交</button>
</div>
</div>
</div>
{{--form表單HTML程式碼--}}
{{--======================================--}}
{{--jQuery處理--}}
<script type="text/javascript">
$(function() {
$("#BTN").on("click", function() {
$.ajax({
type: "post",
url: "{{url("pe")}}",
data: $("#addRole").serialize(), // 序列化form表單裡面的資料傳到後臺
//dataType: "json", // 指定後臺傳過來的資料是json格式
//返回成功返回處理處理
success: function(data){
console.log(data);
// if (data == 0) {
// layer.msg('新增成功!', {icon: 16,shade: 0.01});
// } else {
// layer.tips('新增失敗!', '#BTN', {tips: [2, '#3595CC'], time: 2000})
// }
},
//返回失敗返回處理
error: function(err){
alert("資料異常!");
}
})
})
})
</script></script>
{{--jQuery處理--}}

</body>
</html>
以上程式碼在laravel框架8版本中使用可以正常打通,
前後臺後臺處理完資料之後返回json格式(json資料具備通用性)資料

$data['code'] = 0;

return json_encode($data);