I store JSON data in HTML hidden fields on the server side. Then I'd like to retrieve that data using Javascript and JQuery on the client side. The problem is that I get a JSON string instead of a JSON object.
This is my code on the server side:
<form id="data" style="display: none;">
<input id="channels" type="hidden" tal:attributes="value python: view.context['ChannelManager'].toJSON(view.channels.values())" />
<input id="mediaGroups" type="hidden" tal:attributes="value python: view.context['MediaGroupManager'].toJSON(view.mediaGroups.values())" />
</form>
This is my code on the client side:
copy.channelList = new ChannelTest();
copy.channelList.fromJSONObjectAll($("#data input[id=channels]").val())
So I get JSON string instead of JSON object from this, $("#data input[id=channels]").val().
How could I get JSON object without converting JSON string in JSON object?
Thanks in advance!
JSON.parse(jsonString);
For older browsers that don't have native JSON support, you can simply include json2.js and this will become a usable function.
Or you can skip this step with some server side scripting. You can simply write the JSON into a script tag. It is parsed implicitly by the script tag instead, as raw javascript.
<script type="text/javascript">
var myObj = <%= myJsonString %>;
console.log('we got this value: '+ myObj.myValue);
</script>
Related
I have the following issue:
I get from my mongodb an dict document, I parse it to json and pass it trough with jinja to my html page. I try to use this json document with the renderjson package. I have tried some solutions with quote the jinja object but it's working not properly.
<div id="test"></div>
<script type="text/javascript" src="static/renderjson.js"></script>
<script>
var str = "{{meta[1][0]}}" // meta is my list, the json object is the first element from flask
document.getElementById("test").appendChild(
renderjson(JSON.stringify(str))
);
</script>
The json is valid.
I am trying to use the renderjson package. https://github.com/caldwell/renderjson.
If I use instead stringfy the parse method, nothing is displayed.
How can I pass the json to the frontend properly?
I have a JSON file as data.json and I have an HTML file with JavaScript embedded in it. I want to access data from the JSON file in a simple HTML(file:///C:/Users/XYZ/Desktop/htmlpage.html) file and NOT in a server-client manner(http://....). I have tried following simple code to import JSON file.
<!DOCTYPE html>
<html>
<body>
<p>Access an array value of a JSON object.</p>
<p id="demo"></p>
<script type="text/javascript" src="F:/Folder/data.json">
var myObj, x;
x = data[0].topic;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
I have read this method of using
<script type="text/javascript" src="F:/Folder/data.json">
on other StackOverflow Questions. But it is not working.
Please tell me the simplest way to access the data in the JSON file.
You could try writing something like this in your JSON file in order to assign the data to a variable:
window.data = JSON.parse('insert your json string here');
You can then access window.data in your page's javascript. You can also omit window. and just assign and/or read from data, which is the same as window.data.
Perhaps a cleaner approach would be to use an AJAX request either with jQuery or vanilla Javascript, both approaches have many answers available on this site.
You could also look into a solution with jQuery.getJSON(): Loading local JSON file
If you are able to use PHP for your desired task (accessing data from JSON file and doing some stuff with data) it will be easier to use PHP to open JSON files. You can use following code to access JSON files.
<?php
$str = file_get_contents('data.json');
$json = json_decode($str, true);
?>
Here $json will be the outermost object (if file starts with '{') / array (if file starts with '['). Then you can use it in a regular way.
Maybe some of you can think that why I'm posting PHP solution in Javascript question? But I found this very much easier than opening file in Javascript. So if you are allowed to use PHP go with that.
I am sending my HTML file to the client in node.js as shown below
app.get('/get', function(req, res) {
res.render(index.html);
});
Here, index.html refers to a json file.
How can I send both together or refer the json file in the client?
If you don't want to request the JSON file from the client as an independent HTTP request you can do one of the following:
Full server side rendering:
Use a template technology like moustache or handlebars, and try to render that data inline with the response. For example if you your JSON file returns a name and an address the index.html could look like:
<div>
<span>Name: {{name}} </span>
<address>Address: {{address}} </span>
<div>
Then when rendering you could pass a js object with properties name and address to the template and you wouldn't need to ask for the JSON file separately. This example follows moustache guidelines just in case I wasn't explicit enough.
Inline object
A bit like the previous solution but less elegant, you can add the full JSON response as an object with within a script tag, and then use it however you see fit. Try to append a block to he HEAD of index.html like this:
<script>
var myObject = <contents of your JSON object>
</script>
The other possible solution was just described in another answer.
I hope this helps.
HTTP only sends one resource at a time. If your page is requesting a JSON file, it needs to be served as a second request.
Alternatively, you can render HTML with a <script> block that has a variable assignment with your JSON-encoded data as a value.
You can't send two types of files back in a single request, but you could either do an ajax call in the html to get the json you need:
<script type="text/javascript">
var json_data;
$.getJSON("URL_HERE", function(data) { json_data = data; });
</script>
or add the json to the html as a javascript object via a template engine (jade shown below):
script(type="text/javascript").
var json_data = #{ JSON.stringify(JSON_OBJECT_HERE) }
I'm developing a shortned url project . And I would use a javascript function to display a pie diagram .
I want to know if it's possible to pass a list of Javabean (jst , jsp ) to a javascript function ( array , table..) ?
One efficient way to achieve this is to create a JSON structure on server side and pass it on to the client side. I suppose your chart data will be in an array or tabular format.
There are various JSON libraries available like Jackson. Refer to Jackson example.
Once you have constructed appropriate JSON object on Server side, you can refer to it on JSP by assigning the value in one line call.
<script type="text/javascript">
var jsonObj = '<c:out value="${jsonObject}"/>';
// you can refer to jsonObj in rest of the script
// including external JavaScript file
</script>
In above example jsonObject is constructed on server side in Servlet or controller etc.
This is format of JSON data: [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}] that I receive through getjson from server. I need to append json with user input. I am trying to do it in this way: 1st convert it into javascript object, append it with user input, again convert to json object & send it back to server for database update. I have converted json to javaScript object using eval(). Now not able to manipulate javascript object. If I convert javascript object back to json object, it displays correctly all data that was sent from server.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input></p>
<p><input type = "button" id = "send" name = "send" value = "send"
onClick="ADDLISTITEM();"></input></p>
<select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{// this script suffers from errors on eval/JSON.parse methods
alert (json.length);//outputs corrcet with eval
tring = JSON.stringify(json);//outputs corrcet with eval
alert(jsonString);//outputs corrcet with eval
alert(json.options[0]);//no output
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script src="http://www.json.org/json2.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = eval(jsonData);
//json = JSON.parse(jsonData);/*error if uncomment:"IMPORTANT: Remove this line from
json2.js before deployment"*/
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script>
</body>
</html>
In jQuery, $.getJSON()'s callback gets called with parsed JSON data; just use it.
$.getJSON("*.php", function(data) {
$.each(data, function() { alert(this.options); });
);
should give you an alert for every {"options": "xyzzy"} object in the array.
EDIT after OP edited their post:
Your edit clarifies things a little: You won't get any data back -- and it will be completely silent, too, as I found out -- if you violate the same origin policy.
Basically (with exceptions (preflight checks, etc)), you can only access URLs on the exact same domain via AJAX. If your HTML file is a static file served locally, it can not access http://127.0.0.1/; if your file is http://foo.baz.quux.org/, you can't simply AJAX into http://mordor.baz.quux.org .
I don't think the problem here has anything to do with eval/parse etc or the same origin policy. Your json is an array of objects each containing a member named options. Therefore you cannot do json.options[0], you have to do json[0].options.
var json = [{"options":"smart_exp"}, {"options":"user_int"}, {"options":"blahblah"}]
for (var i = 0; i < json.length; i++){
alert(json[i].options)
}