php - Laravel 中的 Ajax 请求返回一个空对象

标签 php jquery mysql ajax laravel

我正在使用 Laravel 和 jQuery 将数据插入MySQL 表中并取回新行的新 ID .问题是我得到一个空对象作为响应。我也尝试过 print_r 我的 Controller 中的结果,但我得到了一个巨大的数组。

这是一些代码。

jQuery :

        $.ajax({
            url: "locations/new",
            type: "get", //send it through get method
            data:{name:name,description:description},
            success: function(response) {
              $data = $(response);
              console.log($data);                 
            },
            error: function() {
              console.log("Unable add")
            }
        }); 

Controller :

$name= Input::has('name') ? Input::get('name') : null;
        $description= Input::has('description') ? Input::get('description') : null;

        $add = Location::add($name, $description);

        return  $add;

和我的模特:

    public static function add($name,$description){

       $location_id = DB::table('locations')->insertGetId(
        array('name' => $name, 'description' => $description)
        );
        Self::get($location_id);      
    }

    public static function get($location_id){
        $result = DB::table('locations')->where('location_id',$location_id)
                  ->select(DB::raw('location_id,name'));

        $result->get();

        return $result;

    }

我知道我这里可能有误。请除了你的答案,我想知道错误的原因。

提前致谢..

最佳答案

在共同调查 (@chat) 之后,问题似乎出在查询构建器中。

添加 var_dump($result) 后输出为:

Error: Syntax error, unrecognized expression: object(Illuminate\Database\Query\Builder)#248 (27) { ["connection":prot

我建议删除 DB::raw 函数,因为您可以将字段传递给 select 函数,并且出于方便的原因,可以将 ->get() 函数附加到同一条线。所以最终的查询生成器代码将是:

$result = DB::table('locations')->where('location_id',$location_id)->select('location_id',‌​'name')->get();

这解决了问题。

更新 - 原因

在深入了解框架的源代码后,我发现:

/**
 * Set the columns to be selected.
 *
 * @param  array  $columns
 * @return $this
 */
public function select($columns = array('*'))
{
    $this->columns = is_array($columns) ? $columns : func_get_args();
    return $this;
}

所以 select 函数需要一个数组或参数作为 columns,当 db::raw 被使用时 - 它返回了一个与 select 函数的预期参数冲突的字符串。

关于php - Laravel 中的 Ajax 请求返回一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30181085/

相关文章:

javascript - 正则表达式 : Extract number that's wrapped in

php - 计算列中的所有值

php - 我如何使用 JQuery Ajax 调用服务器端的 PHP 文件以返回并执行 javascripts?

javascript - 如何使div在滚动条上淡入/淡出

mysql - 如何修改外键或主键列的数据类型?

php删除文件夹并使用一个提交删除按钮从mysql数据库中删除一行

php - MySQL 查询枚举

javascript - 使用键盘按键导航网页(在内容脚本内)

php - 是否有任何钩子(Hook)来定义新的 wp-config 常量?

jquery - 当访问者选项卡选择元素时如何更改样式?