首页 > 解决方案 > 如何使用 Laravel 4.2 中的 URL::action 方法使用 JavaScript 函数将变量视图传递给控制器

问题描述

选择值是从下拉列表中分配的。该值作为参数传递给 javascript myFunction。我想使用数据库中的数据在视图中创建一个表。当我不传递参数时,代码工作正常并创建表。但我想传递一个参数。帮帮我,伙计们。

这是我的代码

 function myFunction($choice) {
    document.getElementById("demo").innerHTML = "You selected: " + $choice;

    $.get("{{ URL::action('CombinationController@readData',array('choice'=> 'choice'))}}", function (data) {
        $.each(data, function (i, value) {
            var tr = $("<tr/>");
            tr.append($("<td/>", {
                text: value.student_id
            })).append($("<td/>", {
                text: value.initials + " " + value.last_name
            })).append($("<input />", {
                type: 'checkbox', value: value.student_id
            }))

            $('#student').append(tr);
        });
    });
}

这是路线中的代码

 Route::get('readData/{choice}','CombinationController@readData');

这是我的组合控制器

public function readData($choice)
{
    if($choice==0) {
        $StuPS1ch1 = CombinationSubmits::join('student', 'combination_submits.student_id', '=', 'student.student_id')
    ->select('combination_submits.student_id', 'student.initials', 'student.last_name')
    ->where(['choice_1' => 'PS1'])
    ->get();
    }
    return $StuPS1ch1;
}

标签: javascriptlaravellaravel-4

解决方案


当你的视图被渲染时,php 已经完成了所有代码的编译。到您的 javascript 函数运行(客户端)时,您的 URL(由服务器端的 PHP 生成)已经是一个字符串,因此您不会获得想要的效果。

如果您尝试使用动态段生成 url,如下所示:

URL::action('CombinationController@readData',array('choice'=> $choice))

你可能会得到一个错误,因为 PHP 的 URL 外观要求 $choice 变量在渲染时可用。

我建议将变量更改为查询字符串,因此您可以执行以下操作:

function myFunction(choice) {
    document.getElementById("demo").innerHTML = "You selected: " + choice;

    $.get("{{ URL::action('CombinationController@readData') }}?choice=" + choice, function (data) {
        $.each(data, function (i, value) {
            var tr = $("<tr/>");
            tr.append($("<td/>", {
                text: value.student_id
            })).append($("<td/>", {
                text: value.initials + " " + value.last_name
            })).append($("<input />", {
                type: 'checkbox', value: value.student_id
            }));

            $('#student').append(tr);
        });
    });
}

此外,您还必须更改控制器:

public function readData()
{
    $choice = \Request::input('choice');
    if($choice==0) {
        $StuPS1ch1 = CombinationSubmits::join('student', 'combination_submits.student_id', '=', 'student.student_id')
    ->select('combination_submits.student_id', 'student.initials', 'student.last_name')
    ->where(['choice_1' => 'PS1'])
    ->get();
    }
    return $StuPS1ch1;
}

推荐阅读