|
Hi guys,
Not been here for a while
I have an issue with CORS:
What I am trying to do is load content from a html file into a div.'home.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
The project structure is:
The code inside index.htmlCode:www ---- index.html ---- home.html ---- css -------- style.css ---- js -------- index.js
Code:<div id="page-content"></div> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(document).ready( function() { $("#page-content").load("home.html"); }); </script>
The code inside home.html
I'm expecting index.html to showCode:<h1>Hello</h1>inside theCode:<h1>Hello</h1>Note: I do not have a web server and will not be able to run one so setting headers is not possible?Code:<div id="page-content"></div>
Thanks
CORS is annoying because its enforced by the browser. Also big thing is that .load() is for loading the <script></Script> portion of the html file and executing it so it would never render your <h1>
Script Execution
When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:
Here, any JavaScript loaded into #a as a part of the document will successfully execute.
1
$( "#a" ).load( "article.html" );
However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:
1
$( "#b" ).load( "article.html #target" );
Additional Notes:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
The easiest way to do this would be to load the file into a string and use javascript or jquery to set the div content to that string.
https://api.jquery.com/jquery.get/Code:$.get( "home.html", function( data ) { $("#page-content").html("data"); });
Thanks for the answers, I have fixed this by changing my browsers security settings.
You're correct - I had to change security settings in my browser to get this working. So I'm all good now
It's not as simple as that, to "load a file into a string" you'd need to use a XMLHTTPRequest and that'll get blocked by cors.
This doesn't work as it uses XMLHTTPRequest, see previous reply.
As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object.
« Previous Thread | Next Thread » |
Thread Information |
Users Browsing this ThreadThere are currently 1 users browsing this thread. (0 members and 1 guests) |