找到你要的答案

Q:undefined error on accessing json/object from laravel controller to ajax call

Q:从laravel控制器Ajax调用访问JSON /对象未定义的错误

I am trying to manipulate an object/ json return from the controller in ajax jquery success method.

My codes looks like this -

On controller:

$product_code=$_GET['p_id'];        
$productdata=Product::select('id','product_name','unit_measure','cost_price'
  )->where('product_code','=',$product_code)->get();    
    return $productdata;    //return object         
    return $productdata->toJson();//return json

On view(ajax call):

success: function(data){ 
  console.log(data);
  console.log(data["product_name"]);
  //for json [ console.log(data.product_name);
},

Data has been received successfully but don't know why I am getting undefined error for accessing those data as above. Thanks in advance!

This is what I am exactly getting when trying with json. Output in the console:

[{"id":3,"product_name":"computer network","unit_measure":"piece","cost_price":500}]
undefined

我试图操纵从Ajax jQuery的成功方法的控制器对象/ JSON返回。

我的代码看起来像这样—

在控制器:

$product_code=$_GET['p_id'];        
$productdata=Product::select('id','product_name','unit_measure','cost_price'
  )->where('product_code','=',$product_code)->get();    
    return $productdata;    //return object         
    return $productdata->toJson();//return json

在视图(Ajax调用):

success: function(data){ 
  console.log(data);
  console.log(data["product_name"]);
  //for json [ console.log(data.product_name);
},

Data has been received successfully but don't know why I am getting undefined error for accessing those data as above. Thanks in advance!

这是我确切地在JSON。控制台输出:

[{"id":3,"product_name":"computer network","unit_measure":"piece","cost_price":500}]
undefined
answer1: 回答1:

Is undefined because response object is in array, this should work:

console.log(data.0.product_name);

由于响应对象在数组中,所以不定义,这应该工作:

console.log(data.0.product_name);
javascript  jquery  json  ajax  laravel