jquery - 让 Laravel 返回 JSON

标签 jquery json ajax laravel laravel-5

您好,我正在努力获取 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;

          }

                }

这是我的 Controller 代码

  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 很菜鸟,所以对我宽容点

谢谢!

最佳答案

你错了。在 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()->json() 需要一个数组。 Laravel 将返回具有正确 mime 类型的 JSON 响应。

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

关于jquery - 让 Laravel 返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37127182/

相关文章:

javascript - 为什么我在控制台中得到 'undefined'?

javascript - 在 CSS 媒体打印查询中自定义模态高度和宽度

php - MySQL 到 JSON(与 NVD3.js 一起使用)

javascript - 实时时钟 javascript 从我的自定义时间开始

javascript - 下拉语义-UI : Keep the button value by change event

javascript - Firefox 没有从 JavaScript 设置 css 样式?

jquery - Jstree 在加载时打开特定分支

java - BlackBerry Web 服务 JSON 解析

javascript - 如果数据类型是 JSON 为什么 MIME 类型 'application/json' 会被拒绝?

javascript - AJAX/APACHE/PHP/HTACCESS 配置