[英]Calling a controller function in javascript that will store an entry in a database using ajax (Laravel 4)
我試圖使用ajax調用單擊后在JavaScript中(在Laravel 4中)調用控制器函數的路由,將條目存儲在數據庫中。
我有一個資源“藝術家”,由“ ArtistsController”控制。 我進行呼叫的視圖在“藝術家”目錄中稱為“ show.blade.php”(即頁面顯示了不同的藝術家:Artists / 1,Artists / 2等)。
我還有一個名為“ fanartists”的表格,我想在其中存儲這些數據。 基本上,當用戶單擊特定藝術家頁面上的按鈕時,我希望該關系存儲在此表中。
以下是相關代碼:
show.blade.php:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '*****************',
status : true,
cookie : true,
oauth : true
//xfbml : true
});
$( '.opener' ).click(function() {
FB.ui({
method: 'feed',
link: 'http://crowdtest.dev:8888/artists/',
name: 'Hello',
caption: 'Hello',
description: 'Hello!'
});
request = $.ajax({
url: "/artists/fbclick",
type: "post",
data: serialised data
});
});
};
</script>
<a class="add-list-button-no-margin opener" style="color: white; font:14px / 14px 'DINMedium','Helvetica Neue',Helvetica,Arial,sans-serif;">Play my city</a>
ArtistsController:
public function fbclick($id) {
$artist = Artist::find($id);
$fanartist = new Fanartist;
$fanartist->artist_id = $artist->id; //the id of the current artist page (i.e. artists/1, id=1)
$fanartist->fan_id = Auth::user()->id;
$fanartist->save();
}
路線:
Route::get('/artists/fbclick', array('uses' => 'ArtistsController@fbclick'));
當我包含ajax請求時,FB提要不會彈出。 當我刪除它時,它會。 另外,它沒有像我想要的那樣將數據存儲在數據庫中。
您在這里看到任何問題嗎? 非常感謝您的幫助。 謝謝。
我在您的腳本中看到一些小錯誤。
在您的ajax請求中,您使用post
作為方法,但是您已將路線定義為get
因此可以將路線更改為post
或將ajax方法更改為get
。 我將使用post
路線,因此您的新路線是Route::post('/artists/fbclick', array('uses' => 'ArtistsController@fbclick')');
而且ajax數據字段應采用json格式,因此現在您的ajax請求將看起來像這樣
$.ajax({
url: "/artists/fbclick",
type: "post",
data: {field_name :'data'}
});
終於有了控制器功能,並進行了更改
public function fbclick() {
// $artist = Artist::find($id);
$id=Input::get('field_name'); //field_name is the field name from your Json data
$fanartist = new Fanartist;
$fanartist->artist_id = $id; //the id of the current artist page (i.e. artists/1, id=1)
$fanartist->fan_id = Auth::user()->id;
$fanartist->save();
}
現在一切正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.