I need to generate a JSON object from server containing data to be cached on client. I placed the following:
<script src='Path to js file on server" />
At the server, I generated my json data and placed them inside the JS file.
I can see the generated JSON object on the client-side something as:
var jsonData = [{}, {}];
However, when I try to access jsonData object, it says, undefined!
Is there another way to generate valid javascript from server side?
Thanks
This is the server-side code:
var items = List<myObj>();
string json = JsonConvert.SerializeObject(items, Formatting.Indented);
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendFormat(" var jsonData = {0};", json);
var fileName = Request.PhysicalApplicationPath + "Scripts/Data.js";
System.IO.File.WriteAllText(fileName, sb.ToString());
As for client side:
<script src='#Url.Content("~/Scripts/Data.js")' type="text/javascript"></script>
I tried to use this code on the client:
alert(jsonData[0].Id);
It says, jsonData is undefined!
Regards
ASP part is ok, the problem seemed to lie in javascript variable scoping plane. Possible problems:
You just don't include that js file.
You're trying to access variable before it is initialized;
Variable isn't visible in place, you're trying to access it.
You're not exact in your question and accessing not jsonData, but something like jsonData[0].property
etc.
UPD: Ok, first two options are excluded. Where are you trying to access this variable? Please, show us a portion of code.
Related
I am trying to access the returned object from grrovy controller into my javascript code.
Here's the code.
Groovy Controller:
def result = [
data : 'data',
status : 'success',
]
[result: result]
GSP file:
<g:hiddenField name="result" value="${result}" />
JS file:
var jsresult = $("#result").val();
console.log(jsresult);
console.log(jsresult.data);
Here's the console output:
{data=data, status=success}
undefined
Looks like some issue with formatting but not able to find out the root cause. Tried converting it into JSON but still not able to access the properties (jsresult.data).
Please let me know how I can resolve this and let me know if any alternate way of passing data from groovy controller to JS code.
Thanks.
First, make sure your result is being encoded a proper JSON:
<g:hiddenField name="result" value=${result as JSON}" />
Then parse it in javascript:
var jsresult = JSON.parse($("#result").val());
You'll get an object back that you can interact with as you expect.
As far as other ways to do this: there are quite a few, but for simple and arbitrary data transfer to a static page, this is probably the simplest. If you're using ajax requests you can avoid having to place the JSON-encoded data on your page at all, but from what you included here that does not appear to be the case.
I'm trying to pass initial state from server to client by stringifying that state and storing it in global variable. Below is simplified version of what I'm doing.
// home.tsx
res.render('home', { appState: {script: '<script></script>'} });
// home.pug
doctype html
html
head
script.
window.__initialState__ = !{JSON.stringify(appState)};
body
#root
Sadly the result looks like this
<script>window.__initialState__ = {"script":"<script></script>
which is not valid Javascript. My endgoal is to have server's appState object assigned to window.__initialState__.
The 1st part of your code is very confusing. However, as a general rule, you should always encode any HTML passed from the server to the client as string.
So you need to change the part of your server code that generated the line below:
let scriptObject = {script: '<script></script>'};
to this (assuming that you're using pug and node.js):
var htmlencode = require('htmlencode');
let scriptObject = {script: htmlencode.htmlEncode('<script></script>')};
I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.
#RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
public String getRcaResult(Model model, String flight_id) {
...
JSONObject all = new JSONObject ();
...
model.addAttribute("all",all);
return "dfi/rca";
}
I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:
<script type="text/javascript">
var all= "${all}";
</script>
But if I try the same importing a Javascript file in the JSP, it doesn't get anything:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>
In all.js:
var rcaresults = JSON.parse('${all}');
Are there any way to read the Spring model attributes in a Javascript file?
Thanks in advance.
JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.
If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.
e.g <script>var paramOne =<c:out value="${all}"/></script>
when you use src, your browser (and not your backend) will try to fetch the javascript file from
"${pageContext.request.contextPath}/resources/js/all.js"
so the file is not processed by the server as a ModelView.
I have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/
I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.