This is my index.php
<div class="container">
<h1>Drink A Coffee today</h1> <hr>
<h2>Coffee Orders</h2>
<ul id="orders">
<p><li class="highlight"></li></p>
<p><li class="highlight"></li></p>
</ul>
<h4>Add a Coffee Order</h4>
{!! Form::open(['url' => 'index', 'method' => 'POST']) !!}
<div class="form-group" role="form">
<p>
<label for="name">Name:</label>
<input id="name" type="text" name="name" class="form-control">
</p>
<p>
<label for="drink">Drink:</label>
<input id="drink" type="text" name="drink" class="form-control">
</p>
<p>
<button id="add-order" class="btn btn-default" type="submit">Add!</button>
</p>
</div>
{!! Form::close() !!}
</div>
以下是我的控制器
public function makeOrder() {
$post = Request::all();
if (Request::ajax()) {
$order = new Order;
$order->name = $post['name'];
$order->drink = $post['drink'];
$order->save();
$response = array(
'status' => 'success',
'msg' => 'Option created successfully',
);
return Response::json( $response );
}
}
//Below is my Route
Route::post('index', 'MakeOrderController@makeOrder');
然后是我的Ajax脚本
$(document).ready(function() {
$('#add-order').click(function(e) {
e. preventDefault();
//setting variables based on the input fields
var inputName = $('input[name="name"]').val();
var inputDrink = $('input[name="drink"]').val();
var token = $('input[name="_token"]').val();
var data = {name:inputName, drink:inputDrink, token:token};
var request = $.ajax({
url: "index",
type: "POST",
data: data,
dataType:"html"
});
request.done(function( msg ) {
var response = JSON.parse(msg);
console.log(response.msg);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
});
但是当我尝试提交时,没有任何事情发生,当我检查元素时,我收到此错误&#34;无法加载资源:服务器响应状态为500(内部服务器错误) 请求失败:错误&#34;
答案 0 :(得分:0)
您可以通过在表单上使用jQuery的serialize()函数来简化自己,而不是将每个字段检索为变量。例如:
var data = $(this).closest('form').serialize();
而不是var inputName,var inputDrink等