简体   繁体   中英

jQuery ajax pass success into outside variable

I have a problem using jquery ajax. I have already a js player that works fine without ajax. IE

/jwplayer.js

window.onload = function () {

function etc etc etc

jwplayer('player').setup({
playlist: [{
file: video_url,
}],
width: "640",
height: "380",
autostart: "true",
stretching: "exactfit",
volume: "100",
});
}

PHP page

<script type="text/javascript" src="/jwplayer.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<div id='player'></div>

<script type="text/javascript">
var video_url = some_website_dot_com/file/.m3u8
</script>

This works just fine. But i cant add an ajax function to var video_url . This is the script that i'm trying to make it work

<script type='text/javascript'>
var video_url = function () {
$.ajax({
    type: 'get',
    url: "some_website_dot_com/file/.m3u8",
    dataType: "html",
    success: function (data) {
        var result = data.match(/(http\:\/\/\S+m3u8)/);
        return result[1];
    }
});
}();
</script>

You're trying to return something from an inner function, why not just do this?

var video_url;
$.ajax({
    type: 'get',
    url: "some_website_dot_com/file/.m3u8",
    dataType: "html",
    success: function (data) {
        var result = data.match(/(http\:\/\/\S+m3u8)/);
        video_url = result[1];
    }
});

Update: to get your player created and working when you get the url:

function setupVideo(data) {
    var result = data.match(/(http\:\/\/\S+m3u8)/);
    var video_url = result[1];
    jwplayer('player').setup({
        playlist: [{
            file: video_url,
        }],
        width: "640",
        height: "380",
        autostart: "true",
        stretching: "exactfit",
        volume: "100",
    });
}

$.ajax({
    type: 'get',
    url: "some_website_dot_com/file/.m3u8",
    dataType: "html",
    success: setupVideo
});

A good read on AJAX and specifically the A for asynchronous: How do I return the response from an asynchronous call?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM