从下拉列表中分配选择值,该值作为参数传递给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');
这是我的CombinationController
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;
}
答案 0 :(得分:0)
渲染视图时,php已经完成了所有代码的编译。到您的javascript函数运行时(客户端),您的URL(由服务器端的PHP生成)已经是字符串,因此您将无法获得想要的效果。
如果您尝试生成带有动态细分的网址,例如:
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;
}