Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax loaded content, script is not executing

I am using jquery address plugin for loading pages, but without hash(#).

index.html:

<a href="page.html">Link</a>
<div id="content">

    <script>

        $(document).ready(function() {

            $.address.init(function(event) {

                $('a').address();

            }).change(function(event) {
                // do something depending on the event.value property, e.g.
                console.log(event.value);

                $.ajax({
                    type: "POST",
                    url: event.value,
                    success: function(msg){
                        $('#content').html( $(msg).find("#content").html() );
                    }
                });
            });
            $('a').click(function(e) {
                $.address.value($(this).attr('href'));

            });
        });

    </script>


</div>

page.html:

<div id="content">
    <p>text</p>
    <script>
        $(document).ready(function() {
            alert('loaded');
        });
    </script>

</div>

In #content div will be loaded #content html from page.html(maybe i should use other function, not .html(), correct me please), in that div is script tag, but i dont get alert when that page is loaded from ajax, it works on without ajax loading. Can someone help me ?

EDIT: I am getting this error when i'm trying to click on link with js function:

XMLHttpRequest cannot load javascript:;. Cross origin requests are only supported for HTTP.

DEMO: http://fbstatusi.com/desavanja/kalendar/mesecna_lista

click on link Zurka 123

like image 886
Mirza Delic Avatar asked Nov 12 '22 22:11

Mirza Delic


1 Answers

I've encountered a case when an ajax call would return new HTML that includes the script that needs to execute. The code looked like this:

$.ajax('/url', {
  method: 'get',
  success: function(response) {
    document.getElementById("my-body").innerHTML = response;
  }
});

In that code above, response would contain the script that needs to be executed, but it would not execute. Changing the success callback to the following fixed it:

$("#my-body").html(response);

I'm not sure why that was the case (obviously it has to do with the implementation of .html() method). Perhaps someone could comment with an explanation

like image 98
Dmitry Efimenko Avatar answered Nov 15 '22 12:11

Dmitry Efimenko