1

hi and thanks for stopping.

i already solved my problem, but on my own, so i just want to share my solution and maybe someone has a more elegant way to solve it. maybe its just nice as it is.

so im loading some html via jquery.ajax() and the dataType is html. sometimes a video is placed inside, and the most elegant way for me to embed this, is the jwplayers js embed code, that looks like this:

<script>
    jwplayer("mediaplayer").setup({
        flashplayer: "/player.swf",
        image: "/image.jpg",
        autostart: true,
        'controlbar': 'none',
        file: "/video.m4v",
        width: 752,
        height: 416
    });
</script>

now if i load this, nothing happens, the js just doesnt get executed.

so i ended up putting the js WITHOUT the script tags into a div.

<div id="vc">
    jwplayer("mediaplayer").setup({
        ...
    });
</div>

and then in my ajaxComplete() call i simply move the stuff out of the div and place it in between two script tags.

if ($("#vc").text() !== "") {
    var vjs = $("#vc").text();
    $("#vc").empty().html("<script>"+vjs+"</script>");
}
1
  • 1
    Javascript eval() the function? Commented Feb 22, 2012 at 12:05

2 Answers 2

2

Define a function:

<script type="text/javascript">
    var embedPlayer = function() {
        jwplayer("mediaplayer").setup({
            flashplayer: "/player.swf",
            image: "/image.jpg",
            autostart: true,
            'controlbar': 'none',
            file: "/video.m4v",
            width: 752,
            height: 416
        });
    };
    embedPlayer();
</script>

and then in the success callback you could call this function:

$.ajax({
    url: '/foo',
    success: function(result) {
        $('#container').html(result);
        embedPlayer();
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

oh, i told him to use eval() instead of calling a function! stupid me!
i tried this yesterday (and now again), but i get an "embedPlayer is not defined" if i call embedPlayer() on success.
@Kheu using eval is no more dangerous that what OP is currently doing nor more dangerous that blindly wrapping the code in a function. That is to say, they are all dangerous.
@honk31 - I'm not surprised. If adding code to the page by setting innerhtml doesn't execute the function call inside the code, then I don't see why it would define a function inside the code.
If the parameters, or the whole script must be loaded dynamically, then, there is not much of choice, but to use eval()
1

although it is not recommended, user eval();

if ($("#vc").text() !== "") {
    eval($("#vc").text())
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.