Json响应JS数组

I am trying to develop a mobile app using ionic framework and php. My problem is that I have to show all the registered users. My php code will return the id and name as Json array. I want to receive the array in the following format

 

var profiles = [{
    id: 0,
    name: 'aaa',
 
  }, {
    id: 1,
    name: 'bbb',
   
  }, {
    id: 2,
    name: 'ccc',
 
  }];   

I tried the following code and it is not working  

var profiles = [     {
        str="http://localhost:8888/webapp/api.php?";
            var data = {
                 
                sta : "userdetails"
        };
        $http.post(str,data)
        .success(function (response){
            return angular.fromJson(response);
             
     }}
    )]; 

 

First of all, I can see that you try to read a JSON directly from response which actually is a JSON object (not JSON string). Angular response object has some properties. Check out more in here https://docs.angularjs.org/api/ng/service/$http/

Also, make sure that the server response is actually a valid JSON string http://jsonlint.com/. There is a chance that your response may be a JSON object so you can just directly access your response from response.data.

A valid JSON string is:

"[{"id":0,"name":"aaa"},{"id":1,"name":"bbb"},{"id":2,"name":"ccc"}]"

In case your response is a valid JSON string you can either use angular.fromJson(response.data) or just JSON.parse(response.data)[1] to get your the data you need.

[1] Using JSON.parse instead of angular's function will be better, because you are not binding your code to any framework by using javascript native function. So in case you need to reuse this part of code or rewrite the application you don't also have to rewrite this. ;)