I'm trying to develop a web application with Thymeleaf and I've created an html page that uses an external JavaScript file to change an image URL.But the standard syntax URL:
document.getElementById("im1").src="images/img1.jpg" ;
does not work.Everything else in the JavaScript code works fine.What kind of URL syntax should I use?Thanks in advance.
Try something like :
<script th:inline="javascript">
/*<![CDATA[*/
var context = [[#{/}]];
/*]]>*/
document.getElementById("im1").src=context + 'images/img1.jpg' ;
</script>
Maybe your code didn't reach the image in the context. Debug or use console to see the URL generated from: context + 'images/img1.jpg'. Then try to acess it via your browser. Normaly it should display the image.
Related
I have an asp.net mvc web application , which is deployed under /sites as follow:-
http://servername/sites/
but if i reference the URL as follow:-
url:'/ControllerName/ActionMethodName'
the result will be http://servername/ControllerName/ActionMethodName and NOT http://servername/ControllerName/sites/ActionMethodName
i usually solve this issue inside my razor view by writting the following:-
url: "#Url.Content("~/ControllerName/ActionMethodName")" . but seems that javascript does snot have the same ability. so can anyone advice?
Thanks
There are many ways to solve this, not so elegant.
I prefer to put a Hidden field in _Layout.cshtml (or any other master page)
#Html.Hidden("HiddenCurrentUrl", Url.Content("~"))
In a common js file:
var baseUrl = "";
$(document).ready(function () {
baseUrl = $("#HiddenCurrentUrl").val();
});
Then just refer Urls like this:
$.ajax({
type: 'POST',
url: baseUrl + 'solicitacoes/obtertipo/' + value
})
I'm not sure yet about this practice, but it worked for me (fixing tons of legacy code)
In your javascript file, use variables for all paths.
var ActionSubmit;
In your View include this:
<script>
ActionSubmit = '#(#Url.Content("~/ControllerName/ActionMethodName")';
</script>
Hey guys I am trying to learn how to use JSON files. I understand the basics but I am trying to grasp loading them into an HTML file and I am having a couple of difficulties.
The first difficulty I am having is that if I put in the full file extension to load the file I get an error 'expected hexadecimal digit'. I did some research on it and I think it is because in the file extension it is \u so it is expecting a hexadecimal but I am not sure how to work around it.
The second problem I am having is that if I just use the file extension users.json it works in my editor but not in a browser. It is not loading the file at all, the code is fine (I believe). I think it is just not loading the file because of the file extenion.
Suggestions on how to fix my problems? Thanks in advance.
<body>
for output
<div id="forOutput"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var output;
$(document).ready(function(){
alert("JQuery loaded");
});
$.getJSON('C:\Users\Spencer\Desktop\JSJqueryTesting\JSONTesting\users.json', function(data) {
output = data;
for (var i in data.users) {
alert(data.users[i].firstName + " " + data.users[i].lastName+ " " + data.users[i].joined.month);
}
});
$("#forOutput").html("User 1 lastname: " + output.users[1].lastName);
</script>
The file extension is perfect (.json), however, you can't load local files (because of security reasons). If what you are trying to do, were possible, that would mean any website could access all your local files. Now that's really not such a good idea, and therefore (by default) only files that share the same domain(e.g. stackoverflow.com/*) are allowed. This is called Same Origin Policy.
I'd like to inject a couple of local .js files into a webpage. I just mean client side, as in within my browser, I don't need anybody else accessing the page to be able to see it. I just need to take a .js file, and then make it so it's as if that file had been included in the page's html via a <script> tag all along.
It's okay if it takes a second after the page has loaded for the stuff in the local files to be available.
It's okay if I have to be at the computer to do this "by hand" with a console or something.
I've been trying to do this for two days, I've tried Greasemonkey, I've tried manually loading files using a JavaScript console. It amazes me that there isn't (apparently) an established way to do this, it seems like such a simple thing to want to do. I guess simple isn't the same thing as common, though.
If it helps, the reason why I want to do this is to run a chatbot on a JS-based chat client. Some of the bot's code is mixed into the pre-existing chat code -- for that, I have Fiddler intercepting requests to .../chat.js and replacing it with a local file. But I have two .js files which are "independant" of anything on the page itself. There aren't any .js files requested by the page that I can substitute them for, so I can't use Fiddler.
Since your already using a fiddler script, you can do something like this in the OnBeforeResponse(oSession: Session) function
if ( oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.hostname.Contains("MY.TargetSite.com") ) {
oSession.oResponse.headers.Add("DEBUG1_WE_EDITED_THIS", "HERE");
// Remove any compression or chunking
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
// Find the end of the HEAD script, so you can inject script block there.
var oRegEx = oRegEx = /(<\/head>)/gi
// replace the head-close tag with new-script + head-close
oBody = oBody.replace(oRegEx, "<script type='text/javascript'>console.log('We injected it');</script></head>");
// Set the response body to the changed body string
oSession.utilSetResponseBody(oBody);
}
Working example for www.html5rocks.com :
if ( oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.hostname.Contains("html5rocks") ) { //goto html5rocks.com
oSession.oResponse.headers.Add("DEBUG1_WE_EDITED_THIS", "HERE");
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
var oRegEx = oRegEx = /(<\/head>)/gi
oBody = oBody.replace(oRegEx, "<script type='text/javascript'>alert('We injected it')</script></head>");
oSession.utilSetResponseBody(oBody);
}
Note, you have to turn streaming off in fiddler : http://www.fiddler2.com/fiddler/help/streaming.asp and I assume you would need to decode HTTPS : http://www.fiddler2.com/fiddler/help/httpsdecryption.asp
I have been using fiddler script less and less, in favor of fiddler .Net Extensions - http://fiddler2.com/fiddler/dev/IFiddlerExtension.asp
If you are using Chrome then check out dotjs.
It will do exactly what you want!
How about just using jquery's jQuery.getScript() method?
http://api.jquery.com/jQuery.getScript/
save the normal html pages to the file system, add the js files manually by hand, and then use fiddler to intercept those calls so you get your version of the html file
I'm using MVC3 and building an a tag (link) using jquery. The problem is I can only get my links to work in either prod or dev, not both. Here is my site's url in production.
http://tvap.mydomain.com
This is my development url.
http://localhost/TVAP
So, I have a link that I'm creating via jquery as follows.
var actionCell = $('#itemlist').find(rowId).find(actionCellId);
$('<a>Edit</a>').attr({ 'id': 'edit-' + response.id, 'href': '/Items/Edit/' + response.id }).appendTo(actionCell);
In production, this works, and creates a link as
<a id="edit-17" href="/Items/Edit/17">
But in development (local) it doesn't work as I need this.
<a id="edit-17" href="/TVAP/ItemManagement/Edit/17">
I get the following from
$(location).attr('host') ==> localhost
$(location).attr('host') ==> http://localhost/TVAP/Items/Index
Either too little, or too much info. I'd know I can check for localhost and append TVAP as needed, but this seems like a hack. Another developer may use the ASP.NET VS dev server and get a URL will contain localhost but without the TVAP as I'm getting.
i.e. - http://localhost:64301/Items/Index
This is what I always do in my _Layout.cshtml:
<head>
<!-- other stuff -->
<script type="text/javascript">
window.myProjectName = {
baseUrl : '#Url.Content("~/")'
};
</script>
<!-- other scripts -->
</head>
Then you can always use stuff like myProjectName.baseUrl+"Controller/Action" for accessing your resources from your own javascript files. This helps you separate the views from the javascript, which is a really good thing.
You don't want to mix markup and javascript - and this is a compromise that goes a long way.
If your JS is directly inside your view (as opposed to an external JS file), you can just use Razor to flush URLs into your Javascript.
// untested
var actionCell = $('#itemlist').find(rowId).find(actionCellId);
$('<a>Edit</a>').attr({
'id': 'edit-' + response.id,
'href': '#Url.Action("Edit")/' + response.id
}).appendTo(actionCell);
On clicking hot kyes ctrl+t anywhere from my application it should redirect url to http://localhost:8080/myapp/account/create
i'm doing it by placing .js file in js folder and including that file in every page. thae content of .js file is
jQuery(document).bind('keypress', 'Ctrl+T',function (evt){
window.location.href =("http://localhost:8080/myapp/account/create");
return false
});
where myapp is Controller and create is the Action . so i don't want to hard code the entire url insted, whatever the url, only the controller and action should get replaced. so that in production environment i need not to change the url. this is grails application
As I understand you problem is to pass current context path into javascript, is it?
You can remember current context name in your view (in base layout, for example), put it into your <head> block:
<script type="text/javascript">
window.pageContext = '${request.contextPath}';
</script>
and then use it from other javascript like:
jQuery(document).bind('keypress', 'Ctrl+T',function (evt){
window.location.href = window.pageContext + "/account/create";
return false
});
Or, if you need to generate full path to your controller+action you have to use:
<g:createLink controller="account" action="create" />
see http://grails.org/doc/latest/ref/Tags/createLink.html for more information