【问题标题】:pass a data key value from a json post request to routes to controller将数据键值从 json 发布请求传递到路由到控制器
【发布时间】:2015-07-22 06:44:33
【问题描述】:

我的 json 发布请求有一个名为“id”的数据键,现在我要如何将它从路由传递到我的控制器?

我的 json 发布请求

$.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');

从我的 json 发布请求中可以看到,我已经输入了一个键值名称 id

我的路线

Route::post('employees', [
    'as' => 'employees', 'uses' => 'mot@getemployee'
]);

和我的控制器

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 的键值将被放置并从查询内容中使用的位置。

【问题讨论】:

  • 既然你使用$.post,你应该在你的函数中使用$id = $_POST['id'];而不把它当作参数吗?
  • 你有脚本的实时版本吗?
  • 没问题,能否将您在浏览器控制台中看到的回复添加到您的问题中?
  • 看在上帝的份上,你正在使用一个框架,应该使用 Request::input('id');而不是 $_POST

标签: php jquery json laravel laravel-5


【解决方案1】:

由于您在 jQuery 代码中使用 $.post,因此 {id: ...} 参数作为 POST 数据传递,这意味着不是:

public function getemployee($id){

你应该有:

public function getemployee() {
 $id = (int)$_POST['id']; //notice that int casting

@KhanShahrukh 有一个很好的观点。考虑使用以下代替传统的 POST 变量:

<?php 
namespace App\Http\Controllers;
use Request;
....
....
class ... extends ... {
  public function ...() {
    if(Request::ajax()) { //Prevent direct access
      $id = Request::input('id;);

关于第二个问题(评论中提到),$(this) 不会引用该对象。为了访问对象的属性,您应该在$.each 函数中向function() 添加参数。 (Manual)

所以而不是:

$.each(response.employees, function(){
    $('<option/>', {
        value:$(this).user_no,
        text:$(this).firstname

你应该有:

$.each(response.employees, function(firstname, user_no){
    $('<option/>', {
        value: user_no,
        text: firstname

【讨论】:

  • 谢谢,我还有一个问题,我在列表中添加了“lastname” "$employees = mot_users::where("branch_no", $id)->lists('user_no', 'lastname ', '名');”并尝试使用 "$.each(response.employees, function(user_no, firstname, lastname){ $('', { value:firstname + " " + lastname, text:user_no }).appendTo 显示它(分店名称); });”但它总是只显示选项文本上的姓氏,而不是名字和姓氏的组合。有什么想法和线索吗?
  • 因此您需要传递一个对象数组,其中每个对象都是具有 3 个属性的员工。如果是这种情况,我不知道-&gt;lists() 是否是您正在寻找的东西。 console.debug(response.emp... 的输出是什么?
  • 在控制台日志中,我只得到了 use_no 和 lastname。
  • 它还应该发送名字,而不仅仅是 user_no 和姓氏。有什么线索、想法吗?
  • 您可以按照手册中的示例进行操作,因为您的使用要求非常简单:laravel.com/docs/5.0/queries#selects
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2019-07-26
  • 2017-12-04
  • 2018-02-17
  • 2015-05-19
  • 2019-12-19
相关资源
最近更新 更多