简体   繁体   中英

how can I fetch data from php to my jquery script in a desired json format?

I have a query Select name, age from users and I want it to return the content to jquery with a specific format:

var externalDataRetrievedFromServer = [
    { name: 'Bartek', age: 34 },
    { name: 'John', age: 27 },
    { name: 'Elizabeth', age: 30 },
];

On a php side so far I have:

$fetch = "SELECT name, age from users";
$result = $mysqli->query($fetch);
$data = array();    
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );

and on jquery site I have:

 $.ajax({
            url: './getJson.php', 
            type: "POST",
            data: {
                users: users
            },
            dataType:'text',
            success: function(ans)
            {

                alert(ans);

but it returns me data in a format:

[{"name":"Bartek","age":"34"},{"name":"John","age":"27"},{"name":"Elizabeth","age":"30"}]  

I need the specific format that I mentioned at the beginning of my post, because now my current logic (that I don't want to change) throws me an error: data.forEach is not a function in this line:

function buildTableBody(data, columns) {
        var body = [];

        body.push(columns);

        data.forEach(function(row) {
            var dataRow = [];

            columns.forEach(function(column) {
                dataRow.push(row[column].toString());
            })

            body.push(dataRow);
        });

        return body;
    }

where data is the data in a format that I have right now. So how can I change the format?


A little bit more details here:

I'm using buildTableBody() here:

function table(data, columns) {
            return {
                table: {
                    headerRows: 1,
                    body: buildTableBody(data, columns)
                }
            };
        }

However, when I changed the datatype from text to json, I'm getting the error:

Uncaught TypeError: Cannot read property 'toString' of undefined

from the method buildTableBody .

When I do alert(ans) now, I'm getting:

[object Object],[object Object],[object Object]

Do you have any clues how could I fix it?

---- another edit:

This is exactly what I want to achieve:

var externalDataRetrievedFromServer = [ { name: 'Bartek', age: 34 }, { name: 'John', age: 27 }, { name: 'Elizabeth', age: 30 }, ];

function buildTableBody(data, columns) { var body = [];

body.push(columns);

data.forEach(function(row) {
    var dataRow = [];

    columns.forEach(function(column) {
        dataRow.push(row[column].toString());
    })

    body.push(dataRow);
});

return body;

}

function table(data, columns) { return { table: { headerRows: 1, body: buildTableBody(data, columns) } }; }

var dd = { content: [ { text: 'Dynamic parts', style: 'header' }, table(externalDataRetrievedFromServer, ['name', 'age']) ] }

You are setting dataType:'text' so the response will be returned to success callback as a string.

Since there is no String.prototype.forEach() you get an error

Change to dataType:'json' and jQuery will parse the response to array internally.

It is not shown where you call buildTableBody() to be able to assist any further

forEach for the rows, $.each for the columns.

DEMO HERE: http://jsfiddle.net/0cc3bgp2/

var x = '[{"name":"Bartek","age":"34"},{"name":"John","age":"27"},{"name":"Elizabeth","age":"30"}]';

var rows = $.parseJSON(x);

rows.forEach(function(row) {

    var dataRow = [];

    $.each(row, function(index, value) {
      dataRow.push(value);
    });

    //body.push(dataRow);
    console.log(dataRow);
});

// WILL LOG:
//
// ["Bartek", "34"]
// ["John", "27"]
// ["Elizabeth", "30"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM