laravel 带有参数的laravel ajax动作url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41450837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:03:17  来源:igfitidea点击:

laravel ajax action url with parameters

phpjqueryajaxlaravel

提问by user3844579

I have a problem with an ajax call. The url that i need to get the data is:

我有一个 ajax 调用问题。我需要获取数据的网址是:

localhost/public/getCode?course_id=1&task_id=1

My ajax call is:

我的 ajax 调用是:

function getCode() {
                $.ajax({
                    type: "GET",
                    dataType: 'json',
                    url: "{{action('CodeEditorController@getCode',['course_id'=>$course,'task_id'=>$maintask])}}",
                    success: function (data) {
                        console.log(data);
                    }
                });
            }

But the data returned is empty.

但是返回的数据是空的。

Edit: getCode function:

编辑:getCode 函数:

public function getCode(Request $request)
{
    $code=Code::where('user_id',$user->id)->where('main_task_id',$request->input('task_id'))->first()->code;
    $response = [
        'data' => $code
    ];

    return response()->json($response, 200);
}

What is the issue with my ajax code?

我的 ajax 代码有什么问题?

Thanks!

谢谢!

回答by Alexey Mezenin

One way to do that is to use datafor options:

一种方法是使用datafor 选项:

data: {
    'course_id': {{ $course }},
    'task_id': {{ $maintask }} 
},

To get values in controller you can just use request('course_id')and request('task_id')

要在控制器中获取值,您可以使用request('course_id')request('task_id')

Also it's a really bad idea to use Blade/PHP to build JS. You should use hidden inputs or something to pass data to JS.

使用 Blade/PHP 构建 JS 也是一个非常糟糕的主意。您应该使用隐藏输入或其他东西将数据传递给 JS。