javascript - 如何使用 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;
}
解决方案
当你的视图被渲染时,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;
}
推荐阅读
- python-2.7 - 如何在更广泛的索引之间添加熊猫中的元素
- java - 如何在 Room 中的对象中保留自定义对象
- ios - 我的导航栏是否违反了 IOS 人机界面指南
- r - 如何使用多个变量对多个数据框进行子集化
- linux - .!(|.|git) 在 shell 启动早期导致语法错误,但稍后不会
- apache-poi - 单元格中的“SUM”,带有“POI”(3.17)
- java - 在 VS Code 中导出 jar 文件
- python - Python/Travis-Ci 异常“来自请求 urllib.request.urlretrieve ImportError:未命名模块”
- java - JAXB 不编组循环引用
- c++ - 如果项目被选中,为什么 QGraphicsItem 的孩子不再获得鼠标点击?