Read in javascript a spring controller model - javascript

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.

Related

How to Call Variable from Java to HTML?

I would like to call some variable (code and name -- String) from java class on html class (<label>). And I wonder whether it can be directly applied (without using jsp)? Or it necessary to use javascript?
And if it requires javascript I have added the code below, but it's not working.
<script type="text/javascript">
document.getElementById("lists").innerHTML = name;
</script>
And also this is my java file that store variable code and name.
List<Names> nameList = Common.getNameList(data.getName());
for (int i = 0; i < nameList.size(); i++) {
System.out.println(nameList.get(i).code + "=" + whsList.get(i).name);
}
And in HTML I had,
<div id="lists">
<label>Code<label>
<label>Name<label>
</div>
Please help. Thank you.
No, you can't directly. JavaScript is executed on the client side (browser)
JavaScript is client side scripting lang. and 'Java' run on server side. so you need to send request to server . if you want to use java lang on server side then we need to use servlet or framework like a spring, struts etc.
if you want to use java variable in client side JavaScript then send request to server. you can send request using ajax and send nameList in JSON type from servlet as response then all list available to use in JavaScript ... so you need to refer some example like ...
new link i hope this help
http://www.technicalkeeda.com/jquery/spring-framework-jquery-ajax-request-and-json-response-example

How to use JavaScript variable in Razor?

I try to pass my JS variable into razor, my script fragment:
select: function (event, ui) {
var docID = ui.item.DoctorCode;
#{
string org_code = _unitOfWork.Doctors.GetById("").OrganizationCode;
}
doctorOrgLabel.text('#org_code');
}
In GetById() method i want to pass JS variable docID. I'd appreciate any help!
I try to pass my JS variable into razor
This sentence makes strictly no sense at all.
Razor is a view engine used by the ASP.NET MVC framework running on the server to produce some HTML template.
javascript on the other hand is a client side language running on the client. Once the HTML template is rendered to the client and javascript starts to execute there's no longer such notion as Razor.
If you want to pass some javascript variable to the server you have a couple of options:
make an AJAX call to the server
set the value of this variable in some hidden field inside a form and submit this form
use window.location.href to redirect to the server and passing the variable as query string parameter
store the javascript variable in a cookie which will be sent to the server on subsequent requests

Can I create xml using jQuery or use server side?

Is it possible to create an xml file using jQuery or will I have to use server side functions?
JQuery is a javascript library which runs on the client side/browser. To write to the server you need to use a server side tool. ex. ASP, Python, Php.
You can create xml content for your xml file and then set it in href as base64.
Check this thread:
How to create a dynamic file + link for download in Javascript?
Use jquery ajax to send some data to a server page (ASP.NET/ PHP) and create the XML there.
The below sample makes a call to an ASP.NET MVC action method where i am creating an XML document using the data passed and saving it the disk.I am using the LINQtoXML API for this example
$.post("Home/CreateXML", { name : "Angel", age : "22" } function(data){
alert("Response from server is : "+data);
});
And in your Server side,
public ActionResult CreateXML(string name,string age)
{
XElement elm=new XElement("SomeXML",
new XElement("Name",name),
new XElement("Age",age));
elm.Save("C:\\somexml.xml")
return Content("XML Created and saved in disk!");
}
Executing this will create an XML in this form
<SomeXML>
<Name>Angel</Name>
<Age>Angel</Age>
</SomeXML>

Build a Javascript Widget : can I call an aspx?

I'd like to create my own JS widget, which it must be dinamic.
I mean, for example, the html generated from the downloaded script :
<script src="www.mywebsite.it/widget/?ID=2&Category=4" type="text/javascript"></script>
must be different from :
<script src="www.mywebsite.it/widget/?ID=1&Category=5" type="text/javascript"></script>
and the Data into HTML should be taken from Database, on my server. So, I need to call an aspx page that create javascript that will create html? Or which could be the solution?
The better way is to use generic handler with .ashx, if you want retrieve data from server and send data in JSON or XML.
Next, the data will be inserted in page with javascript.
So, if I understand well, you do generate an .aspx that contains your template and a javascript that hold the code to navigate in Category as this if you use JQuery :
$.ajax({
url: 'data.ashx?ID=2&Category=5',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Server behind (ashx) :
private readonly JavaScriptSerializer _js = new JavaScriptSerializer();
public void ProcessRequest(HttpContext context)
{
//Do logic and retrieve data here
Categorys c = GetFooById(context.Request["id"]);
context.Response.Write(_js.Serialize(c));
context.Response.ContentType = "application/json";
}
It seems that you'd want to use AJAX.
The script source shouldn't be dynamic (it can't be cached if it is), but the script itself could call whatever page you like to pull back data (say in JSON format) or raw markup to place in a pre-defined element.
Don't use the ASPX page to create javascript if you can help it.
Consider using a JavaScript library such as jQuery to help you.

ASP.NET generating Javascript object

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.

Categories