Laravel使用Ajax将数据发布到Controller操作

时间:2015-12-11 16:57:01

标签: laravel laravel-5

我在路由文件中有2个控制器,用于从Ajax获取数据。我想从ajax获取数据并通过post方法在简单的控制器中处理

很遗憾我收到此错误:

BadMethodCallException in Controller.php line 283: 

Method [sendSmsToUser] does not exist.

控制器:

Route::group(['middleware' => 'auth'], function () {
    Route::post('sendSmsToUser', 'NotificationsController@sendSmsToUser');
    Route::post('sendEmailToUser', 'NotificationsController@sendEmailToUser');
});

NotificationsController:

class NotificationsController extends Controller
{
    /**
     * @param Request $request
     * @return boolean
     */
    public function postSendSmsToUser(Request $request)
    {
        $info = User::find($request::input('user_id'));
        $send = SendSMS::sendSms($info->mobile_number, $request->input('message'));
        if ($send) {
            Log::info("sms successfull send to user id" + $request->input('user_id'));
            return true;
        } else {
            Log::emergency("sms dont send to user");
            return false;
        }
    }
}

Ajax请求:

$('[id^="send_sms-"]').click(function () {
    var id = $(this).attr('id').split('-');
    var message = $('#sms_message-' + id[1]).val();
    $.ajax({
        type: "POST",
        cache: false,
        encoding: "UTF-8",
        url: "{{ url('sendSmsToUser') }}",
        data: {user_id: id[1], message: message},
        success: function (data) {
        }
    });
    return false;
});

1 个答案:

答案 0 :(得分:1)

Route::post('sendSmsToUser', 'NotificationsController@sendSmsToUser');正在调用控制器中的函数sendSmsToUser。那种方法不存在。它可能应该是:

Route::post('sendSmsToUser', 'NotificationsController@postSendSmsToUser');