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
Related
I am building an app with Phonegap and jQuerymobile. The app roughly works like this:
1) The app downloads a ZIP file from a public server and then unzips them to a local folder. I got the local folder path from fileSystem.root.toNativeURL() (in OS, it's something like this: file://var/mobile/Container/Data/Application/xxxx/Documents/)
2) App redirects to HTML that was unzipped in local folder (ex: file://var/mobile/Container/Data/Application/xxxx/Documents/index.html)
I am now facing issues b/c inside the index.html file, all the links are absolute path (ex: Link). This breaks all the links since (I assume) they are all now pointing to file://content/index2.html instead of file://var/mobile/Container/Data/Application/xxxx/Documents/content/index2.html.
My question is, how should I handle the links? I am thinking i should just rewrite all the links to force prepend the local folder URL in front of it. Is there a better way?
And if rewriting links is the way to go, how can I do this with jQuerymobile? I did this in jQuery which seems to work http://jsfiddle.net/jg4ouqc5/ but this code doesn't work in my app (jQueryMobile)
When you are loading index.html, you are getting file://some_path/..../index.html as your base URL. Any links which will be encountered now own-wards can be resolved in relation to the base URL.
You would know your scenario better. There could be multiple ways in which this can be fixed.
Have a contract with the CMS/Code generator. Links should always be generated either Relative to the base URL or Absolute. The links you are getting in the page are wrong - Link it ideally should be Link or fully qualified like https://www.google.com.
If you want to change the URL then you can use native code to change it after unzipping the content. It will be really straight forward.
If you want to change the URL in browser then you will have to persist the base url and then take care of couple of things:
a. absolute urls - In your case you can just check the window.location.protocol, if it starts with 'http' and then skip it.
b. sub-directories
Here is a small I have written:
Note: I have not tried this code and you might have to change it according to your need.
$(document).ready(function(){
var base_file_name = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
//In index.html (persist this value in native)
var baseUrl = window.location.href.replace(base_file_name, "");
$("a").each(function () {
this.href = baseUrl + this.pathname;
$(this).click(function (e) {
e.preventDefault();
alert(this.pathname);
window.location.href = this.href;
});
});
});
The example you linked should work, make sure you have the <base> set correctly and that you are using the correct string to replace.
Yeah, your going to have to normalize all URL's when your page loads. I can't test with phonegap right now, but your basePath will need to be one of the following:
The file path as you described in your answer (not likely)
window.location.origin (optionally including window.location.pathname)
CODE:
// mini dom ready - https://github.com/DesignByOnyx/mini-domready
(function(e,t,n){var r="attachEvent",i="addEventListener",s="DOMContentLoaded";if(!t[i])i=t[r]?(s="onreadystatechange")&&r:"";e[n]=function(r){/in/.test(t.readyState)?!i?setTimeout(function(){e[n](r)},9):t[i](s,r,false):r()}})
(window,document,"domReady");
domReady(function () {
var anchors = document.getElementsByTagName['a'],
basePath = /* get your base path here, without a trailing slash */;
Array.prototype.forEach.call(anchors, function( anchor ){
anchor.setAttribute('href', basePath + anchor.getAttribute('href'));
});
});
Remove the forward slash from the beginning of your links.
href="content/index2.html">
we have the following situation:
in default.aspx we have a link:
test.
and the JS code:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
if(data.indexOf("http://")==0)
window.open(data);
else{
var win=window.open();
with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close();
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The callback can first be an url address or 2nd html code that must be executed.
Option 1 fits, but in option 2, a new window will be opened where the code has been written but not executed.
It's clear, since it happens in the stream, it can't be executed. So the question, how can you fix it? Maybe a refresh(), or similar?
Because of the requirement of the customer, the workflow can not be changed, so it must be solved within doPost().
EDIT
The response in case 2 is HTML like this. This part should be executed:
<HTML><HEAD>
<SCRIPT type=text/javascript src="http://code.jquery.com/jquery-latest.js">
</SCRIPT>
<SCRIPT type=text/javascript>
$(document).ready(function() {
do_something...
});
</SCRIPT>
</HEAD>
<BODY>
<FORM>...</FORM>
</BODY>
</HTML>
Please help. Thanks.
In your JS code it should be something like this:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
//if(data.indexOf("http://")==0)
if (data.type!="url") //i will add a data type to my returned json so i can differentiate if its url or html to show on page.
window.open(); // I dont know why this is there. You should
else{
var win=window.open(data.url); //This data.url should spit out the whole page you want in new window. If its external it would be fine. if its internal maybe you can have an Action on one of your controllers that spit it with head body js css etc.
/* with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close(); */ // No need to write data to new window when its all html to be rendered by browser. Why is this a requirement.
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The overall logic is this
You do your ajax call on doPost
Find out if data returned is of type url or anything that need to open in new window
If it is url type it would have a url (check if this is not null or empty or even a valid url) then open a new window with that url. Have a read of W3C window.open for parameters
If you want to open and close it for some reason just do that by keeping the window handle but you can do this on dom ready event of that new window otherwise you might end up closing it before its dom is completely loaded. (someone else might have better way)
If its not url type then you do your usual stuff on this page.
If this does not make sense lets discuss.
I have a Javascript function, where I want to call jQuery.Load() to load a file. How would I get ASP.Net to fill in the local server name, so that I can just give a relative path?
The reason for that is I can give the base, say "http://www.mydomain.com/", however I would like to be able to test locally and not have to publish on every single build. I just want to load a local file.
My first thought was just "/MyFolder/MyPage.aspx", but that did not work. I then thought of "~/MyFolder/MyPage.aspx", but that did not work either.
I figure it should be some sort of ASP.Net directive to prepend, just I am not sure what.
I wanted to give some code to show the actual use and what worked.
<head runat="server">
<script type="text/javascript">
// <![CDATA[
function DoPopupSignin()
{
var urlLoad = "http://" + window.location.host + '/Candiates/Login.aspx';
// Triggering bPopup when click event is fired
$('#popupSigninMaster').bPopup({
//modalClose: false,
//opacity: 0.6,
//positionStyle: 'fixed', //'fixed' or 'absolute'
content: 'iframe', //'iframe' or 'ajax'
contentContainer: '.content',
loadUrl: urlLoad, //Uses jQuery.load()
});
}
// ]]>
</script>
</head>
I am trying to get my jQuery Popup working loading the contents from another file. My code uses the free jQuery popup control that I found jQuery.bPopup.js.
In JavaScript as you are preparing your query, you can use window.location.host.
var path = window.location.host + '/relative/path/file.ext';
$.load(path);
It's a recurring pain, but I use something like this:
public static Uri ToAbsoluteUri(this string path)
{
Uri uri;
if (Uri.TryCreate(path, UriKind.Absolute, out uri)) return uri;
var serverUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
var serverUri = new Uri(serverUrl);
return new Uri(serverUri, path);
}
Controls / Forms in .NET have a ResolveUrl(string) method that will allow you to resolve relative paths using ~/ pathing. Otherwise you use the VirtualPathUtility static class.
We can modify the document root directory path for PHP using
$_SERVER['DOCUMENT_ROOT'] = "to/some/new/directory";
//Now the "/" which represent the ^(above) path
in .htaccess we have
RewriteBase "/to/some/new/directory"
Now, I need to modify the root directory path to use in javascript. How to do it?
Currently, I am declaring a variable containing static path to the my personalized root directory and using it as
var root = "../to/new/path";
document.location = root+"/somepage.php";
Scenario
I think i should tell a little bit about the scenario, for you guys to catch my idea
Default Web Root Directory
http_docs/
inside it contain a main folder
http_docs/application <-- contains the actual application
http_docs/js <-- contains the script
http_docs/index.html
Now, the application also contains ajax feature for updating, editing, loading new content, or other resources, which if accessed at "/" will represent at /some/path/i/called not /application/some/path/i/called,
To come around this problem
I can define a static variable like
var root = "application/";
and use it somewhere like
$.post(....., function(data) { $(body).append("<img src='"+root+"resources/img1.jpg"); });
But for a single use, defining the path as static, might not be a big deal, but, when the application grows, and certain modification would cause me to change all the paths i give in the js part. I thought, it would be sensible, just like, I do it in PHP, using <img src="/resources/img1.jpg" />
I tried my best to explain this question, if still is not understandable, please community, lets help them understand. I welcome you to edit my question.
EDITED: Trying to answer the updated question
Assuming the JavaScript is called included from the index.html file, if you insert a img tag and use relative urls, they will be relative to the path of the index file. So <img src='application/resources/img1.jpg'> would work just fine. If the script should work for several sublevels (e.g. if the page "application/etc/etc2/somePage.html" needs images from "application/resources/")it may be easier to use absolute urls, and you could include a javascript block on every page generated by php that holds the absolute url to the "root" of the application, like:
<!-- included by php in all html pages, e.g. in defautlHeadter.php -->
<script type="text/javascript">
var rootUrl = "<?= getTheRootUrl() ?>";
</script>
Where getTheRootUrl() is a method or server variable that gives the root url you need. If the url is translated/remapped (by apache etc. outside of what is visible to php) you may need to hardcode the root url in the php method but at least it will be only one file to change if you ever change the root directory.
Then you can use the root url to specify absolute paths anywhere in the application/website using rootUrl + "/some/relative/path" in anywhere in the application.
I once made something like this, to set
window.app_absolute = '<?php echo GetRelativePath(dirname(__FILE__)); ?>'
I also use something like this
static function GetRelativePath($path)
{
$dr = $_SERVER['DOCUMENT_ROOT']; //Probably Apache situated
if (empty($dr)) //Probably IIS situated
{
//Get the document root from the translated path.
$pt = str_replace('\\\\', '/', Server::GetVar('PATH_TRANSLATED',
Server::GetVar('ORIG_PATH_TRANSLATED')));
$dr = substr($pt, 0, -strlen(Server::GetVar('SCRIPT_NAME')));
}
$dr = str_replace('\\\\', '/', $dr);
return substr(str_replace('\\', '/', str_replace('\\\\', '/', $path)), strlen($dr));
}
... Something along those lines, hacked up for demonstration purposes.
I wrote a javascript method to display an image dynamically depending on whether or not a plugin is installed or not. Depending on the page, the url might be deep into sub paths and i wanted to see if i can get a path back to the image without all the marky-mark.
Example
myImage src location = {root}/Content/Images/myImage.png
Now call the js to display the image on the following pages. I show the path of the example page and the image element with the src path. Notice how its different depending on how deep we are. If i use an absolute path, then i would have to change it for my test environment and production. I thought I could use ~ but i guess not. Ideas ?
http://mysite.com/sub1/sub2/ -- <img src="../../Content/Images/myImage.png" />
http://localhost:2500/sub1/ -- <img src="../Content/Images/myImage.png" />
The tilde is only relevant for .NET server side code.
An easy way to accomplish what you're looking for is to write the root path out to a javascript variable or function.
For example on the server side on your page:
public string RootPath
{
get
{
return ResolveUrl("~/");
}
}
And then use the following javascript:
<script type="text/javascript">
<!--
function getRoot()
{
return '<%= RootPath %>';
}
// -->
</script>
You can then use the javascript getRoot function to get to the root of the website and use it for your urls.