【问题标题】:Get Laravel to return JSON让 Laravel 返回 JSON
【发布时间】:2016-09-04 18:17:16
【问题描述】:

您好,我正在努力以 JSON 格式获取经过验证的错误消息。我不知道为什么在 laravel 中很难做到这一点。我正在尝试使用 ajax 请求来获取包含表单数据错误的 HTTP 响应。这是我的请求代码

<?php

    namespace App\Http\Requests;

    use App\Http\Requests\Request;

    use Auth;

    use Log;


    class PostRequest extends Request
    {
        /**
         * Determine if the user is authorized to make $this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }

        /**
         * Get the validation $rules that apply to the request.
         *
         * @return array
         */

    public function wantsJson()
        {
            return true;
        }

    public function response(array $errors) 
       {  

            if ($this->ajax())
           {
                return new JsonResponse($errors, 422);
           }
           return $this->redirector->to($this->getRedirectUrl())
                                        ->withInput($this->except($this->dontFlash))
                                        ->withErrors($errors);
    }

    public function rules() {

      $rules = [];

      foreach($this->request->get('address') as $key => $val) {

        $rules['address.'.$key] = 'required';

      }


     foreach($this->request->get('city') as $key => $val) {

        $rules['city.'.$key] = 'required';

      }
  return $rules;
   }


 public function messages() {


  foreach($this->request->get('address') as $key => $val) {


    $messages['address.'.$key.'.required']="*Please fill in the address";

          } 

        foreach($this->request->get('city') as $key => $val) {


             $messages['city.'.$key.'.required']="*Please fill in the city";

         } 
          return  $messages;

          }

                }

这是我的控制器代码

  namespace App\Http\Controllers;

  use Illuminate\Http\Request;

  use App\Http\Requests;

  use App\Http\Requests\PostRequest;

  use Auth;

  class propContoller extends Controller {


     public function __construct() {

           $this->middleware('auth');
     }


     public function main ()  {

             $amount = Auth::user()->units;   // pull amount of units from data base and create forms 

           return view("myprop",compact("amount"));
     }

     public function Postdata(PostRequest $request) {





      }
  }

还有我的ajax请求

$("#from").submit(function(event) {

$.ajax({
  type: 'post',
  url: '/myproperties/save',
  data: { '_token': token, 'data': "good" },
  dataType: 'json',
  success: function(data){
  console.log(data);
  },
  error: function(data){
    var errors = data.responseJSON;
    console.log(errors);
    // Render the errors with js ...
  }

});

和我的 HTML

       <div  class="form-group col-md-6">


                <div  class= "col-md-6  form-group {{ $errors->has('address.'.$i) ? ' has-error' : '' }}">

            <label for={{$id = "Address".$i}}>Address</label>
              <input  value="{{ old('address.'.$i) }}" type="text"  name="address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address">


              @if ($errors->has('address.'.$i))
                          <span class="help-block">
                          <strong>{{ $errors->first('address.'.$i) }}</strong>
                              </span>
                 @endif

                </div>

<div  class="col-md-6 form-group {{ $errors->has('city.'.$i) ? ' has-error' : '' }}">

           <label for={{$id = "city".$i}}>City</label>
            <input value="{{ old('city.'.$i) }}" type="text"  name="city[{{$i}}]"  class="form-control" id={{$id = "City".$i}} placeholder="City">

             @if ($errors->has('city.'.$i))
                       <span class="help-block">
                           <strong>{{ $errors->first('city.'.$i) }}</strong>
                            </span>
                        @endif
                  </div>

有人请帮助我是 laravel 的菜鸟,所以请放轻松

谢谢!

【问题讨论】:

  • 你的问题解决了吗?

标签: jquery json ajax laravel laravel-5.2


【解决方案1】:

你错了。在 Laravel 中创建 JSON 响应非常容易,以便以后您的前端玩具可以使用它。

public function getSomethingById(string $id)
{
    $data = $this->fooRepository
        ->getSomething($id)
        ->pluck('name', 'id')
        ->toArray(); // you don't have to use repository, you can use Eloquent directly here, or DB facade or even hardcode the array.

    return response()->json([
        'count' => count($data),
        'data' => $data // or whatever
    ]);
}

无论您需要什么,只要记住 response()-&gt;json() 需要一个数组。 Laravel 将返回具有正确 mime 类型的 JSON 响应。

然后你可以使用 jQuery 来$.get()你的 AJAX 资源等。

【讨论】:

    【解决方案2】:

    这就是你返回 json 的方式,在 laravel 中它真的很容易

    if($request->ajax()){
        return response()->json($something);
    }
    else
    {
    //return View or whatever
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 2014-04-20
      • 2023-03-20
      • 2021-05-22
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多