Junwha Hong
Junwha Hong

Reputation: 13

I want to load html page in my div tag

 function secondCategory(i) {
      var liName = 's_li_' + i;
      $('#' + liName).click(function() {
        $('.article').load('http://google.com');
      });
    }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

I like to load html page in my div tag, article. but It occur an error "Failed to load 'website adress': Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https."

[http://wedontknow.dothome.co.kr
./index.html
http://google.com][1]

above sites which I had tried occur the error. how can I load html pages?

Upvotes: 0

Views: 904

Answers (2)

John Doe
John Doe

Reputation: 245

You can't load external website unless you own it cause you need to enable cross-origin resource sharing

For local file, this error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost

Upvotes: 1

ethancrist
ethancrist

Reputation: 114

This is really a server-sided issue. I've avoided .load(); solely because of the CORs issue it always brings up. I'd glaze over this: Enable CORs

My recommendation, however, is to put all of your html code as strings in a JS file. This isn't as elegant and can be messy, but it's fast and easy to move around thereafter.

var html = '<div id="div-id"><p>Hi there!</p></div>';

$('#target-div').html(html);

That's always how I do things, although you could start to get some ridiculously long strings. You could concatenate them like so so it's easier to read:

var html = 
'<div id="wrapper">' +
    '<div id="inner">' +
        '<p>Hello!</p>' +
    '</div>' +
'</div>';

$('#target-div').html(html);

Not the prettiest thing to look at, but I've written entire full-blown web apps like this, it never presents security issues (namely, CORs) and is blazing fast.

Using this method with multiple servers

Assuming you have a say in what the other server's response will be, you could always do a good ole post request.

var postData = {
    optionalData: 1234
};

$.post('https://google.com', postData, function(res) {
    $('#target-div').html(res)
});

Upvotes: 0

Related Questions