所以基本上我想在Laravel中用AJAX建立一个调查。 但是当我尝试提交它时,在控制台中我看到这个错误“baseUrl not defined”。请记住,我的jscript是外部的。虽然如果需要我可以把它放在刀片内。
这是我的JScript代码
$(document).ready(function(){
$('#submitanketa').click(function(){
var uneto = $('input[name="radio"]:checked').val();
var token = $('#token').val();
$.ajax({
method: "POST",
url: baseUrl + "/post/post/ajax",
data: {
unos: uneto,
_token: token
},
success: function (data, xhr) {
/* location.reload();*/
console.log();
console.log(xhr);
$('#form1').html("<h1 class='hanketa'>Hvala na glasanju!</h1>");
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
});
以下是我对调查的看法
<fieldset>
<div id="form1">
<legend class='legenda'>Koliko sebe smatrate humanim?</legend>
<label class="container1">1
<input type="radio" checked="checked" name="radio" value="1">
<span class="checkmark"></span>
</label>
<label class="container1">2
<input type="radio" name="radio" value="2">
<span class="checkmark"></span>
</label>
<label class="container1">3
<input type="radio" name="radio" value="3">
<span class="checkmark"></span>
</label>
<label class="container1">4
<input type="radio" name="radio" value="4">
<span class="checkmark"></span>
</label>
<label class="container1">5
<input type="radio" name="radio" value="5">
<span class="checkmark"></span>
</label>
<button id="submitanketa" >prijavi</button>
<input type="hidden" name="id" value="form1" />
<input type="hidden" name="MM_insert" value="form1" />
<input type="hidden" value="{{csrf_token()}}" id="token">
</div>
</fieldset>
路线相关
Route::post('/post/post/ajax', 'AnketaController@anketa');
这是控制器
class AnketaController extends Controller{
public function anketa(Request $request)
{
$glasanje = $request->get('unos');
$id_kor= session()->get('user')->id;
$proba = new Anketa();
$proba->glasanje = $glasanje;
$proba->id = $id_kor;
$rez = $proba->ubacianketu();
}}
相关模型
class Anketa
{
public $id;
public $glasanje;
public $id_glasanje;
public $id_korisnik;
public $datum_glasanja;
public $odgovor;
public function ubacianketu()
{
$rez = DB::table('anketa')
->insert ([
'ocena' => $this->glasanje,
'id_kor' => $this->id
]);
return $rez;
}
}
JQuery加载到模板中。
答案 0 :(得分:1)
它给出错误,因为在baseUrl变量之前你没有定义baseUrl变量所以首先在你的ajax脚本中输入codedefine baseUrl变量,如下所示
var baseUrl =&#34; {{URL :: to(&#39; /&#39;)}}&#34;;