jQuery ajax将成功传递给外部变量

时间:2015-10-23 19:45:16

标签: javascript jquery ajax

我使用jquery ajax时遇到问题。我已经有一个没有ajax工作正常的js播放器。即。

/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页面

<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>

这很好用。但我无法向var video_url添加ajax函数。这是我试图让它工作的脚本

<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>

1 个答案:

答案 0 :(得分:2)

你试图从内部函数返回一些东西,为什么不这样做呢?

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];
    }
});

更新:在获取网址时创建并运行您的播放器:

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
});

关于AJAX的详细阅读,特别是异步的A:How do I return the response from an asynchronous call?