I have been looking into designing my UI with bootstrap table. My simple HTML utilizes bootstrap table features to render a response from REST service.Everything looks good as long as my REST service responds with list of objects as a JSON array.
My question: How do I use bootstrap table if the response JSON does contain only a single element.
Sample response JSON that works:
{
"parent":
[{
"id":1,
"name":"some_name",
"city":"some_city"
}]
}
Sample JSON response that I am struggling to display:
{
"parent":
{
"id":1,
"name":"some_name",
"city":"some_city"
}
}
I tried one workaround to fix this by appending array brackets in the JSON response using following:
function responseHandler(res) { //this function is called from table element
return JSON.parse("["+JSON.stringify(res.parent)+"]");
}
However, I don't really like this solution as it looks like making things work without a systematic approach.
Based on my research, I am pretty convinced that bootstrap table requires the JSON data in JSON array format. I have run some tests and it confirms this finding.
I would like to know how do I achieve showing single element JSON response using bootstrap-table features like "data-url" annd "data-response-handler".
My HTML looks like:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Template</title>
<script src="bootstrap-table-master/docs/assets/js/jquery.min.js"></script>
<script src="bootstrap-table-master/docs/assets/bootstrap/bootstrap.min.js">
</script>
<script src="bootstrap-table-master/dist/bootstrap-table.js"></script>
<link rel="stylesheet" href="bootstrap-table-master/docs/assets/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="bootstrap-table-master/docs/assetsbootstrap/css/bootstrap-min.css">
<link rel="stylesheet" href="bootstrap-table-master/dist/bootstrap-table.css">
<script>
function responseHandler(res) {
return JSON.parse("["+JSON.stringify(res.parent)+"]");
}
</script>
</head>
<body>
<h1>Bootstrap Table</h1>
<table id="table" data-toggle="table" data-url="mydata.json" data-height="699" data-response-handler="responseHandler">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="name">Name</th>
<th data-field="city">City</th>
</tr>
</thead>
</table>
</body>
</html>
Related
I'm trying to proxy to a certain API endpoint that returns an html page but I get the error
Access to font at 'https://data.domain.com/v3/assets/fonts/glyphicons-halflings-regular.woff2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET https://data.domain.com/v3/assets/fonts/glyphicons-halflings-regular.woff2 net::ERR_FAILED
Inside my angular app, I have three different targets that I am proxying to. The first two proxies work fine but the other is a bit weird.
My proxy.conf.json file looks sth like this...
{
"/API": {}, // First proxy works fine
"/info": {}, // Second proxy fine too
"/data": {
"target": "https://data.domain.com/v3/uk",
"secure": false,
"pathRewrite": {
"^/data": ""
},
"changeOrigin": true,
"logLevel": "debug"
}
}
So inside my data service, I define a variable data that contains the path '/data' and I pass that as the path in my POST request like so...
private data = '/data';
public fetchData(data: Data) {
return this.http.post(this.data, data, {responseType: 'text');
}
Upon making that post request, I'm expecting the returned value to be some html code that I'd like to bind to my template. Herein lies the problem. You see, the returned HTML looks something like this...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Page</title>
<!-- Bootstrap -->
<link href='https://fonts.googleapis.com/css?family=Ubuntu:300' rel='stylesheet' type='text/css'>
<link href="https://data.domain.com/v3/assets/css/bootstrap.min.css" rel="stylesheet">
<link href="https://data.domain.com/v3/assets/css/loading-bar.min.css" rel="stylesheet">
<link href="https://data.domain/v3/assets/css/custom.css" rel="stylesheet">
</head>
<body
<p class="title">Page Title</p>
</body>
</html>
See that bootstrap import? I think that's what's causing the problem because inside the bootstrap.min.css code, references to the glyphicons-halflings-regular font are made like so...
url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype')
Hence for each of those font formats, I get the exact same error repeated.
How can I solve this?
I am working on a simple webpage. I have a following sample json file and an HTML template
data.json
{
"NAME":"SAMPLE_NAME",
"ADDRESS":"New Brunswick Avenue"
}
index.html
<div class="name"></div>
<div class="address"></div>
So i have to display the name and address on the template reading from the json file. Is there any library that i can user for this or any other way to accomplish this?
I think you are looking for a compile-time templating or pre-compiled templating engine sort of thing.
You can build one your own with html, css and using javascript or jquery to change the text of certain elements, but this is going to take a long time if you have big pages.
However there is a library out there that does something like this and its called Handlebars.
Heres a link: http://berzniz.com/post/24743062344/handling-handlebarsjs-like-a-pro
This might give you an idea of what it does: What is the difference between handlebar.js and handlebar.runtime.js?
Here is an example using your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// Load your html / template into this variable
var template = '<div class="name">{{name}}</div><div class="address">{{address}}</div>';
var jsonData = {
"name":"John",
"address": "City Street"
}
var compiledTemplate = Handlebars.compile(template);
// The output html is generated using
var html = compiledTemplate(jsonData);
document.getElementsByTagName('body')[0].innerHTML = html;
</script>
</body>
</html>
If you would rather write html outside of the javascript variables you could also do it like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="template">
<div class="name">{{name}}</div>
<div class="address">{{address}}</div>
</div>
<script>
// Load your html / template into this variable
var template = document.getElementById('template').innerHTML;
var jsonData = {
"name":"John",
"address": "City Street"
}
var compiledTemplate = Handlebars.compile(template);
// The output html is generated using
var html = compiledTemplate(jsonData);
document.getElementById('template').innerHTML = html;
</script>
</body>
</html>
Can anyone help me to identify the problems I might have?
It seems that I cannot use angular even though I have imported the library. When I refresh HTML this is what shows in the browser. It seems that the controller is not working at all. Also even when I try to do {{1+1}}. It won't do any calculations for me instead just showing "{{1+1}}". This has been bugging me for three days. Really appreciate someone can give me a tip.
This is my HTML file:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<meta charset ="utf-8">
<meta http-equiv="X-UA-Compatible" content= "IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container" ng-Controller="AppCtrl">
<h1>UE Call Home</h1>
<table class ="table">
<thead>
<tr>
<th>HostIP</th>
<th>IMSI</th>
<th>IMEI</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = "device in ue">
<td>{{device.hostid}}</td>
<td>{{device.imsi}}</td>
<td>{{device.imei}}</td>
<td>{{device.model}}</td>
</tr>
</tbody>
</table>
</div>
<script type="javascript" src="Controller/controller.js"></script>
<script type="javascript" src="angular.min.js"></script>
</body>
This is my controller:
var myApp = angular.module('myApp',[]);
myApp.controller('AppCtrl',['$scope','$http',function($scope,$http){
console.log("Hello World!");
ue1 ={
hostip:"andrew",
imsi:909090,
imei:898989,
model:8994
};
ue2 ={
hostip:"nick",
imsi:787878,
imei:565656,
model:8996
};
ue3 ={
hostip:"dick",
imsi:1212121,
imei:2323232,
model:9650
};
var ue =[person1,person2,person3];
$scope.ue = ue;
}]);
First declare the angular link before your JavaScript link
And also the variables person1, person2, person3 needs to be changed to ue1, ue2, ue3
You have to change the order of <script> declaration as below,
<script type="javascript" src="angular.min.js"></script>
<script type="javascript" src="Controller/controller.js"></script>
Also replace the ng-Controller with ng-controller
In addition to that verify the angular.min.js path, better to put the controller.js and angular.min.js in same folder to avoid path conflict.
I am new to JSON. I ran the code below and got an error
import urllib2
import json
urllib2.urlopen('https://ciapipreprod.cityindextest9.co.uk/TradingApi')
print json.load(urllib2.open(`https://ciapipreprod.cityindextest9.co.uk/TradingApi'))
ValueError: No JSON object could be decoded
But when I ran it without json as below, I could see what was inside.
import urllib2
data=urllib2.urlopen('https://ciapipreprod.cityindextest9.co.uk/TradingApi')
html = data.read()
print html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Ajax Test Harness</title>
<link href="/TradingAPI/Content/css?v=oI5uNwN5NWmYrn8EXEybCIbINNBbTM_DnIdXDUL5RwE1" rel="stylesheet" type="text/css" />
<link href="/TradingAPI/Content/themes/base/css?v=M29VGAPKJl__Ya5hV5ngguUfY8uNXwB076bG-JmFavY1" rel="stylesheet" type="text/css" />
<script src="/TradingAPI/Scripts/js?v=lYEohN8Pq3__VMPgz6C4ZXSyFUc0d6gVJQ28Wflqo3E1"></script>
</head>
<body>
<div style="width: 100%; margin: 0px;">
<img alt="CityIndex Logo" src="/TradingAPI/Images/ci_white_logo.jpg"/>
</div>
<h2>Ajax Test Harness</h2>
<script src="/TradingAPI/Scripts/tradingApi.js" language="javascript" type="text/javascript"></script>
<script src="/TradingAPI/Scripts/corsTest.js" language="javascript" type="text/javascript"></script>
<script src="/TradingAPI/Scripts/json2.js" language="javascript" type="text/javascript"></script>
<div id="apitest">
<form id="form1" runat="server"></form>
<hr />
<h2>Test Harness</h2>
<button onclick=" eval($('#code').val()); ">Execute</button><br />
<textarea id="code" cols="120" rows="15">
var userName = "DM631479";
doPost('/session',{ "UserName": userName, "Password": "password"}, function (data, textCode) {
// Smoke Test
doGet('/smoketest');
setRequestHeader("UserName", userName);
setRequestHeader("Session", data.Session);
// Authentication Test
doGet('/smoketest/authenticated');
// Account Information Tests
doGet('/useraccount/DM631479/ChartingEnabled');
doGet('/useraccount/ClientAndTradingAccount');
// Need Valid Test Data doPost('/useraccount/Save', {"PersonalEmailAddress":"not#realaddress.com","PersonalEmailAddressIsDirty":true})
// Cfd Markets Test
doGet('/cfd/markets?marketname=uk&maxresults=10&usemobileshortname=true');
//Logoff
doPost('/session/deleteSession?userName='+userName+'&session='+data.Session);
});
/* var userName = "DM631479";
cityindex.corsTesting.doPost('/session',{ "UserName": userName, "Password": "password"}, function (data, textCode) {
});*/
</textarea>
<br />
<select id="result" style="background-color: #e4e4e4; min-height: 300px;" multiple="multiple"></select>
<hr />
</div>
</body>
</html>
My understanding was that if there were '{}' within my var 'Data' they were "dictionaries" and I could then call them using the JSON module.
Perhaps I have misread the contents of my variable and maybe there actually isn't anything for JSON to 'load'
Sorry if any of the tagging here is wrong or ineligible.
Looks to me like that url returns html, and not json at all. Also, from the print statement, results it doesn't look like there is any json embedded in the page at all.
json.load will only work with input that looks exactly like json, something that looks like a dictionary. It won't pull this out of the surrounding html.
If there were json somewhere on that page, say, in a script tag, the you'd first have to parse the html to extract it. You could use beautiful soup or scrapy for that.
JSON has a particular specified shape which that response does not conform to. What you have there is JavaScript (and some JavaScript is valid JSON) embedded in HTML. It's similar to this example:
<pre><code>print("Hello World")</code></pre>
which contains Python code, but is not, in total, valid Python code. In order to extract the data you will need to find a different endpoint to hit that produces valid JSON (or else you will have to extract the JSON-like parts of the JavaScript on the page that you are interested in by using the html.parser built into the standard library, a library like bs4, or regular expressions). Then you can feed the valid JSON text to json.loads and work with it.
I know there's quite a lot of info already on stackoverflow regarding ngTable/AngularJS, but I tried everything, and it just doesn't work.
my html is this:
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<title>Sequencing experiments overview</title>
<script src="/LIMS/angular-1.2.14/angular.js"></script>
<script src="/LIMS/js/controllers.js"></script>
<script src="/LIMS/ng-table-master/ng-table.js"></script>
<link rel="stylesheet" href="/LIMS/ng-table-master/ng-table.css" />
<link data-require="bootstrap-css#*" data-semver="3.0.0" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="/LIMS/style.css" />
</head>
<body ng-app="dataOverview" ng-controller="searchCtrl">
<div>
Search: <input ng-model="query">
<p><strong>Page:</strong> {{tableParams.page()}}
<p><strong>Count per page:</strong> {{tableParams.count()}}
<table ng-table="tableParams" class="table">
<tr ng-repeat="exp in $data | filter:query">
<td data-title="'id'">
{{exp.id}}
</td>
<td data-title="'name'" sortable ="'name'">
{{exp.name}}
</td>
<td data-title="'Type'">
{{exp.type}}
</td>
</tr>
</table>
</div>
</body>
</html>
my controller.js file is this:
var dataOverview = angular.module('dataOverview', ['ngTable']);
dataOverview.controller('searchCtrl', function searchCtrl($scope, $http, ngTableParams) {
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 5 // count per page
},{
getData: function($defer,params) {
$http.get('/LIMS/index_query.php').
success(function(data, status) {
var orderedData = data;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(),params.page() * params.count()));
})
}
})
});
The index_query.php returns a valid JSON object queried from a MySQL DB (will not show this here).
So, this code is almost ok i guess. It displays a table with columns and values from the DB. I can filter using the value in the filter box. However, it only shows 5 rows, and there are no buttons to go to the next 5 rows or increase the number of rows on the page. As described on the ngTable page (http://bazalt-cms.com/ng-table/example/1).
When checking console with firebug, I see an 'Uncaught TypeError: Cannot call method 'push' of undefined ' error. I assume it;s an error populating the array which should build the buttons to go from 1 page with 5 records to another? I wasted 10h on this today, so please enlighten me, I would be very grateful.