this is doing my head in a bit.
Under ASP5 MVC6 I have not been able to get JQuery to be sourced.
I have set the app.UseStaticFiles(); it is set set before the useMVC() as below
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseApplicationInsightsRequestTelemetry();
HttpService.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
app.UseApplicationInsightsExceptionTelemetry();
app.UseSession();
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
});
app.UseMvc();
}
my layout file seems to be serving up the .css fine but not the scripts. I can even navigate/view through the browser to the relative js file it loads the text in the browser.
Visual studio always has the same message though ( even though the path is correct )
07:27:35.4149: Referenced file '~/lib/jquery/dist/jquery.min.js' not found.
07:27:35.4149: Referenced file '~/lib/bootstrap/dist/js/bootstrap.min.js' not found.
in my layout:
<body>
#await Component.InvokeAsync("Navigation")
#RenderBody()
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
#RenderSection("scripts", required: false)
Embarrassingly enough I was simply missing a #section scripts { } on one of my pages and was being distracted by the fact that debugger kept saying it couldnt find the .js at the file path.
I dont know why the vs2015 debugger constantly says it cant reference the file, but it does work properly now when its launched..
Related
I'm using Spring Boot 2.7.5, Java 8 and Maven and have the following jars included in pom.xml:
spring-boot-devtools
spring-boot-starter-data-jpa
spring-boot-starter-test
spring-boot-starter-tomcat
spring-boot-starter-web
tiles-core
tiles-jsp
tomcat-embed-jasper
I want to use JQuery and DataTables. My static content is in src/main/resource/static:
src/main/resources
bootstrap-5.2.2-dist/
DataTables/
jquery-ui-1.13.2.custom/
jquery-3.6.1.min.js
myapp.css
myapp.js
I have a configuration class that has this
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { ... })
public class ApplicationConfiguration implements WebMvcConfigurer
{
#Override
public void addResourceHandlers(
ResourceHandlerRegistry registry)
{
registry//
.addResourceHandler("/static/**")//
.addResourceLocations("/static/");
}
}
In my JSP, I have tried the following, none of which work
<script type="text/javascript" src="jquery-ui-1.13.2.custom/jquery-ui.min.js"></script>
<script type="text/javascript" src="static/jquery-ui-1.13.2.custom/jquery-ui.min.js"></script>
<script type="text/javascript" src="/static/jquery-ui-1.13.2.custom/jquery-ui.min.js"></script>
In my application.properties, I have this:
spring.mvc.view.prefix=/WEB-INF/content/
spring.mvc.view.suffix=.jsp
server.servlet.context-path=/myapp
What am I missing or doing wrong?
Found a way to make it work. Not the best answer, but it is an answer (cue Wheel of Time quote):
I moved the static folder directly under the webapp folder. I then changed the script and link tags to have the src/href start with "static/".
I have no idea why this works but am still open to finding the right way to do it.
I am trying to complete an exercise for one of my courses and my HTML file won't link with my Javascript file. I put the link between my HTML file and my Javascript file in the body of my HTML file but the files still won't connect. When I test this code in Microsoft Edge, the buttons simply do not work. Anybody know what the problem is?
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Page</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<button onclick = "startWorker()">Start Worker</button>
<button onclick = "stopWorker()">Stop Worker</button>
<ul id = "output">
</ul>
<script type = "text/javascript" src = "/js/script.js"></script>
</body>
</html>
Javascript
var worker;
function startWorker(){
worker = new Worker ("js/mod4_worker.js");
worker.onmessage = function(event){
document.getElementById("output").innerHTML += '<li>' + event.data + '</li>';
};
}
function stopWorker(){
worker.terminate();
}
Files
So, I would try my comments :
Change the script.js path to : "../js/script.js"
Change the worker passed script to "../js/mod4_worker.js"
As GGG said, using a path starting with "/", a slash, use the path from root. The full path is either :
Windows : file://DriveLetter:\REST_OF_PATH
Unix/Linux/OSX : file:///REST_OF_PATH
WebServer : http://domain/REST_OF_PATH
If the structure is from /webapp/ :
html/index.html
js/script.js
Accessing script.js from index.html needs to go back one folder (..) and then set the path seen here (js/script.js) which gives (../js/script.js) OR using full path (/webapp/js/script.js) which I wouldn't recommend because if you change "webapp" directory of location or URL (on WebServer)
Remove the / from your src in the index.html. So it should be
src = "js/script.js"
Why? When you begin the src value with a /, that means you're referring to an absolute path (in other words, it starts the path from your drive's root). My devtools shows it as
file:///C:/js/script.js
By removing the first / in your src, you're now doing relative pathing, and it will look in the correct place.
Permissions & File locations
(Stumbled on this Q and here's the only way I solved it...)
For me, I found it was a permissions and file location issue...
I'm running a local webserver on Ubuntu 18 Desktop, working with dev from a local folder linked to the web directory: /var/www/html/MY_DEV -> /home/me/MY_DEV. So, the www-data user couldn't actually "own" them like it needed to.
I use this setup just fine for PHP, HTML, and CSS just fine. But, if I include a javascript file via src="", no matter what I do, it doesn't work.
The only way I could get it to work on my desktop is if BOTH the served file (somefile.php or somefile.html) are physically at /var/www/html/...
And, of course accessing them at localhost/...
And, of course owning them obsessively with sudo chown -R www-data:www-data /var/www/html
I have 2 Razor .cshtml files that have a similar structure like the following:
<script type="text/javascript" src='#Url.Content("~/Scripts/jqwidgets/jqxcore.js")'></script>
<script type="text/javascript" src='#Url.Content("~/Scripts/jqwidgets/jqxdata.js")'></script>
<script type="text/javascript" src='#Url.Content("~/Scripts/jqwidgets/jqxbuttons.js")'></script>
...
<More header stuff (different in both files)>
<script language="javascript" type="text/javascript">
function commonFunctionForJqWidgets() {
...
callSomethingFromJqWidgetsLibrary();
...
}
</script>
I am writing common code for these 2 files and would like to put the common code in another .js (or .cshtml) file instead of duplicating it in both places. However, the common code requires including some of the jqwidgets includes since it calls library functions for it.
What would be the proper way to handle this? Should I simply add a new .cshtml file, move all of the includes in there, and then define my common functions in there as well?
Usually when you have common UI code, you may put that inside a partial view which can be included in other views as needed. But in your case, It is more like a bunch of javascript files you want in multiple files. So you may create a script bundle which will have all those scripts and use that in your pages as needed.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
// Your existing bundles here
bundles.Add(new ScriptBundle("~/bundles/jQxWidgets")
.Include(
"~/Scripts/jqwidgets/jqxcore.js",
"~/Scripts/jqwidgets/jqxdata.js",
"~/Scripts/jqwidgets/jqxbuttons.js",
"~/Scripts/SomeOtherCustomJsfileRelatedtojQxWidgets.js"));
}
}
And in your specific views, you can include this inside the Scripts section.
#section Scripts
{
#Scripts.Render("~/bundles/jQxWidgets")
}
Or if you have more than just the scripts as your common stuff, create a partial view and include your common stuff there and include this partial view in your other views as needed.
Create a partial view called CommonGrid.cshtml inside your ~/Views/Shared folder
<h2>Common header for both the pages </h2>
#section Scripts
{
#Scripts.Render("~/bundles/jQxWidgets")
}
And in your other views
UserList.cshtml
<h1>Users</h1>
#Html.Partial("CommonGrid")
ProductList.cshtml
<h1>Products</h1>
#Html.Partial("CommonGrid")
You can also make your CommonGrid strongly typed to a view model and create a property in your page specific view model of this type(of CommonGrid's viewmodel) and pass that in the Html.Partial method.
I am following this example to include a SkyScanner widget on my website:
http://business.skyscanner.net/portal/en-GB/Documentation/Widgets
For some reason I just get an empty div - could this be something to do with the key? When I clicked on the activation link I got from SkyScanner for the widget key, I got a page saying the following:
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be
viewable on remote machines, please create a tag within
a "web.config" configuration file located in the root directory of the
current web application. This tag should then have its
"mode" attribute set to "Off".
I have created a web.config file with the following code:
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
I've had a look at 'inspect element' on Chrome and get the error
Uncaught TypeError: Object # has no method 'write'
api.ashx?key=[KEY]:1
This is the JS:
var API_KEY = 'b7290ac3-1f9f-4575-88a7-89fed0c61f7f',
MAIN_URL = 'http://api.skyscanner.net/api.ashx?key=' + API_KEY;
function main(){
console.log('loaded module');
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
};
function newWrite(str) {
$(str).appendTo('body');
}
var oldWrite = document.write;
document.write = newWrite;
function onMainSkyscannerScriptLoad(e) {
console.log('loaded main script');
skyscanner.loadAndWait('snippets', '1', {'nocss' : true}, main);
}
$('button').click(function() {
console.log('getting main script');
$.getScript(MAIN_URL, onMainSkyscannerScriptLoad);
});
I also used this to personalise the widget:
skyscanner.load("snippets","2");
function main(){
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setShape("box300x250");
snippet.setCulture("en-GB");
snippet.setCurrency("USD");
snippet.setColourScheme("classicbluelight");
snippet.setProduct("flights","1");
snippet.setProduct("hotels","2");
snippet.setProduct("carhire","3");
snippet.draw(document.getElementById("snippet_searchpanel"));
}
skyscanner.setOnLoadCallback(main);
Skyscanner B2B support engineer here. Are you still having trouble with this?
For the quickest response, please contact us here: http://business.skyscanner.net/portal/en-GB/Home/Contact
The first thing to check is that the file is on a web server (localhost is fine), and not loaded from the desktop (or local disk in general). This is because some of the Skyscanner JS code looks up other files using URLs like //api.skyscanner.net. In other words, saving the file to the desktop and opening it from there will not work (will show as an empty div). Here's the most basic example of drawing a widget. Can you try putting this in a file and accessing it through a server? If it works we can build on it :)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="//api.skyscanner.net/api.ashx?key=b7290ac3-1f9f-4575-88a7-89fed0c61f7f"></script>
<script type="text/javascript">
skyscanner.load("snippets","2");
function main(){
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setShape("box300x250");
snippet.setCulture("en-GB");
snippet.setCurrency("USD");
snippet.setProduct("flights","1");
snippet.setProduct("hotels","2");
snippet.setProduct("carhire","3");
snippet.draw(document.getElementById("snippet_searchpanel"));
}
skyscanner.setOnLoadCallback(main);
</script>
</head>
<body>
<div id="snippet_searchpanel" style="width: auto; height:auto;"></div>
</body>
</html>
I'm working with ASP.Net MVC4 wiht view engine Razor. I like put mask date and time in TexBoxFor I installed for nugget jquery.maskedinput-1.3.min.js and add in the view
(document).ready(function () {
$("#FechaDen").mask("99/99/9999");
$("#HoraDen").mask("99:99:99");
});
But I have this error: Uncaught TypeError: Object [object Object] has no method 'mask'
How I can resolve this problem?
You seem to have forgotted to reference the jquery.maskedinput plugin in your page:
<script type="text/javascript" src="#Url.Content("~/scripts/jquery.maskedinput-1.3.min.js")"></script>
Make sure that the path is correct and that the plugin is actually situated in this folder. Use the Network tab of a javascript debugging tool such as FireBug to ensure that there are no 404 errors with your script references.
Also make sure that you have added this script inclusion after jQuery. Be careful because in the ASP.NET MVC 4 Internet Project Template, the ~/Views/Shared/_Layout.cshtml file renders jquery as a bundle at the end of the DOM:
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
So if you are putting this reference inside your view make sure that this happens inside the scripts section:
#section scripts {
<script type="text/javascript" src="#Url.Content("~/scripts/jquery.maskedinput-1.3.min.js")"></script>
<script type="text/javascript">
$("#FechaDen").mask("99/99/9999");
$("#HoraDen").mask("99:99:99");
</script>
}
Also notice that since this script is now at the end of the DOM I have gotten rid of the $(document).ready call which is no longer necessary (and which you got wrong in the code you have shown because you forgot to prefix it with a $).