Jquery datatables display image in one of the colu

2019-01-20 06:31发布

问题:

I am using Jquery data tables and getting the data from server using Ajax. Basically the data I am sending is about an Order and there are different types of orders.

What I am trying to achieve is send in the Order type along with the order data and on the client side display an image.

I have two main types, Surplus and Deficit. I have both images as my static content on the client side and from server I am able to get the data. I am not sure how to display it.

This is how I get data from server

$('#matchOrderedTable').dataTable({
    "ajax": {
        "url": TippNett.Api.Url + "Match/DataTable",
        "data": function (d) {
            d.token = authToken;
        }
    },
    "columns": [
        { "data": "Created" },
        { "data": "Amount" },
        { "data": "OrderOrg" },
        { "data": "OrderMatchedOrg" },
        { "data": "OrderLoc" },
        { "data": "OrderMatchLoc" },
    ]
});

and my View looks like this

<table id="matchOrderedTable">
    <thead>
        <tr>
            <th>@Texts.Created</th>
            <th>@Texts.Amount</th>
            <th>@Texts.Organizations</th>
            <th>@Texts.MatchedOrg</th>
            <th>@Texts.Locations</th>
            <th>@Texts.MatchedLoc</th>
        </tr>
    </thead>
</table>

Any ideas or examples on how to do that?

回答1:

Try using the columns.render property so that you can create a custom function to do your logic for checking the order type and then return the correct string representation of your image.

Example (updated to match comment below)

In your table declaration code add a column for the order type

$('#matchOrderedTable').dataTable({
    "ajax": {
        "url": TippNett.Api.Url + "Match/DataTable",
        "data": function (d) {
            d.token = authToken;
        }
    },
    "columns": [
        { "data": "Created" },
        { "data": "Amount" },
        { "data": "OrderOrg" },
        { "data": "OrderMatchedOrg" },
        { "data": "OrderLoc", render: getImg },
        { "data": "OrderMatchLoc", render: getImg }
    ]
});

Column render function code. The data property stores the row data as an object so use that to access the order type value.

UPDATE: even though there is no column for OrderType you can still access the object's value in the data param.

function getImg(data, type, full, meta) {
        var orderType = data.OrderType;
        if (orderType === 'Surplus') {
            return '<img src="image path here" />';
        } else {
            return '<img src="image path here" />';
        }
    }

Hopefully that helps.