weixin_33725239 2019-10-09 20:24 采纳率: 0%
浏览 30

Ajax回拨和Laravel

I have created an API which my AJAX post send values to it. AJAX does post and my laravel API does process the values. My issues is with the callback returning the value back to my AJAX post. My AJAX doesn't return the results in the success section when I do console log. I would like the results from my api to can use data to make my condition. At the moment, the console log doesn't even return a value. But in my chrome inspector under preview it shows the response from my API but not in the success section.

AJAX

var fname = "Joe";
var lname = "Test";
var processUrl = "api.example.com/z1";
$.ajax({
    type: 'POST',
    url: processUrl,
    data: {"name": fname,"surname": lname},
    dataType: 'json',
    success: function(res){
      console.log(res);
      if(res.length >= 1){
        $('#display').val(res.name);
      }
   }                            
});

PHP

public function checkResults(Request $request){
  $name = $request->name." ".$request->surname;

  $result = array();
  $result['name'] = [$name];

  return response()->json($result,201);
}
  • 写回答

3条回答 默认 最新

  • weixin_33726943 2019-10-09 21:38
    关注

    I believe this is happening because you are sending status code 201 (Created), but you need to send status code 200 (OK) to trigger the success callback.

    public function checkResults(Request $request){
      $name = $request->name." ".$request->surname;
    
      $result = array();
      $result['name'] = [$name];
    
      return response()->json($result,200);
    }
    

    I couldn't find it specifically in the jQuery docs, but this SO question addresses it.

    评论

报告相同问题?