通过ajax Request

时间:2017-04-10 05:42:09

标签: php ajax laravel-5.2

当通过ajax选择时,我将单选按钮的值传递给控制器​​。控制器中的验证失败,表示该字段是必需的。我记录了带有beforeSend中值的dataString。它记录了所选单选按钮的值。我还检查了网络选项卡的请求,其中包含请求有效负载中的数据。我不明白这里导致错误的原因。

<input type="radio"  name="port_type" id="low-risk" value = "low-risk" >

if ($('#low-risk').is(":checked")) {
    var p_type = $(this).val();
    console.log(p_type);
    showFunds(p_type);

}

这是具有ajax函数的函数

    function showFunds(p_type){
        var hello = p_type;
        //console.log(p_type);
        var dataString = 'p='  +hello;
        //console.log(dataString);
        $.ajax({

        type: "POST",
        url: "/showFunds",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: dataString,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend : function(){
          console.log('logging BS');
          console.log(dataString);
        },
        success: function(data) {
            console.log(data);
        },
        error : function(xhr ,status ,error)
        {
            console.log(xhr);
        },

        });
      }

这是我的控制器

 public function showFunds(Request $request){

        $validator = \Validator::make($request->all(),[
            'p' => 'required',
            ]);

        if ($validator->fails()) {

            //return response()->json(['msg'=>'val_fail']);
            return response()->json(['msg'=>$validator->errors()]);
        }

        else{ }

验证者未能发送错误&#34;需要p字段。&#34;

1 个答案:

答案 0 :(得分:0)

试试这个:

    function showFunds(p_type){
    var hello = p_type;
    //console.log(p_type);
    var dataString = JSON.stringify({p: hello});
    //console.log(dataString);
    $.ajax({

    type: "POST",
    url: "/showFunds",
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
    data: dataString,
    cache: false,
    contentType: false,
    processData: false,
    beforeSend : function(){
      console.log('logging BS');
      console.log(dataString);
    },
    success: function(data) {
        console.log(data);
    },
    error : function(xhr ,status ,error)
    {
        console.log(xhr);
    },

    });
  }