Php 将json post请求中的数据键值传递给路由控制器
我的json post请求有一个名为“id”的数据键,现在我如何将它从路由传递到我的控制器 我的json post请求Php 将json post请求中的数据键值传递给路由控制器,php,jquery,json,laravel,laravel-5,Php,Jquery,Json,Laravel,Laravel 5,我的json post请求有一个名为“id”的数据键,现在我如何将它从路由传递到我的控制器 我的json post请求 $.post("/employees", {id:"1"}, function(response){ if(response.success) { var branchName = $('#branchname').empty(); $.each(response.employees, function(){ $('<option/>
$.post("/employees", {id:"1"}, function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(){
$('<option/>', {
value:$(this).user_no,
text:$(this).firstname
}).appendTo(branchName);
});
}
}, 'json');
还有我的控制器
public function getemployee($id){
$employees = employees::where("branch_no", $id)->lists('firstname', 'user_no');
return response()->json(['success' => true, 'employees' => $employees]);
}
正如您所看到的,我有一个参数$id,据推测,它是json post请求中名为id的键值的放置位置,并将从查询内容中使用。由于您在jQuery代码中使用了
$.post
,因此,{id:…}
参数作为post数据传递,这意味着:
public function getemployee($id){
你应该:
public function getemployee() {
$id = (int)$_POST['id']; //notice that int casting
$.each(response.employees, function(firstname, user_no){
$('<option/>', {
value: user_no,
text: firstname
@KhanShahrukh有一个很好的观点。考虑使用以下代替传统的邮政变量:
<?php
namespace App\Http\Controllers;
use Request;
....
....
class ... extends ... {
public function ...() {
if(Request::ajax()) { //Prevent direct access
$id = Request::input('id;);
你应该:
public function getemployee() {
$id = (int)$_POST['id']; //notice that int casting
$.each(response.employees, function(firstname, user_no){
$('<option/>', {
value: user_no,
text: firstname
$。每个(response.employees,function)(名字,用户名){
$('', {
值:用户号,
文本:名字
既然您使用的是$.post
,您是否应该使用$id=$\u post['id']
在函数内部,而不是将其作为参数处理?您是否有该脚本的实时版本?没问题,请将您在浏览器控制台中看到的响应添加到您的问题中?让我们来看看。看在上帝的份上,您使用的是框架,应该使用Request::input('id');而不是$_post谢谢,我还有一个问题,我补充道“lastname”在列表“$employees=mot_users::where”(“branch_no”,$id)->列表('user_no','lastname','firstname');”上,并试图用“$.each”(response.employees,function(user_no,firstname,lastname){$('',{value:firstname+”“+lastname,text:user_no})来显示它;});“但它总是只显示选项文本上的lastname,而不显示firstname和lastname的组合。有什么想法和线索吗?所以你需要传递一个对象数组,其中每个对象都是一个具有3个属性的雇员。我不知道->lists()如果是这种情况,您需要的是。console.debug的输出是什么(response.emp…
?在控制台日志中,我只得到了use_no和lastname。它还应该发送firstname,而不仅仅是user_no和lastname。有什么线索和想法吗?您可以按照手册中的示例进行操作,因为您的使用请求非常简单: