简体   繁体   中英

How to call Laravel controller function from JavaScript

How i can call controller function using JavaScript !?

Controller:

public function archive($id)
{
  $article = Article::find($id);

  $article->public = 0;
  $article->archive = 1;

  $article->save();
}

Route:

Route::post('/archive/{id}', 'HomeController@archive');

I would be grateful for any working options. Thank you!

I believe you also need to create response for your controller if you want to access it via api also.

// put this above your class name
use Illuminate\Http\Request;

public function archive(Request $request, $id)
{
  $article = Article::find($id);

  $article->public = 0;
  $article->archive = 1;

  $article->save();

  return response()->json([
    'success' => 'yes',
  ]);
}

Use jQuery ajax if you are using jQuery

$.post('/archive/' + {your_id}, function(response) {
    // handle your response here
    console.log(response);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM