2016-10-03 43 views
0

我在我的網站上有一個視頻嵌入代碼,但有時目標網址(視頻主機)已關閉!在這些時候,我的網站很長一段時間都在等待連接,並且最終沒有加載視頻..這是一次糟糕的體驗!如何根據我在jquery中的url狀態加載div

我可以從我的主機加載視頻,但出於某種原因,我想嵌入該視頻。但我想我可以用jquery檢查目標網址,如果這是成功的話,可以追加嵌入代碼,否則將視頻追加到我的主機中。

這是我的嵌入代碼(碼1):

<div id="14750915864459730"> 
<script type="text/JavaScript" src="https://www.example.com/embed/dl4ue?data[rnddiv]=14750915864459730&data[responsive]=yes"></script> 
</div> 

這是我的ownhosted視頻(代碼2):

[video width="1920" height="1080" mp4="http://www.mywebsite.com/wp-content/uploads/2016/09/americ.mp4"][/video] 

兩個代碼的是HTML(上WP)

現在我想要的是這樣的:

if https://www.example/... is reachable 
then: load code 1 
else: load code 2 

也是當網址檢查是需要超過2秒只是加載代碼2.

任何人都可以幫忙?

回答

0

$.ajax({ 
 
    // This tries to access the external video 
 
    url: 'https://www.example.com/embed/dl4ue?data[rnddiv]=14750915864459730&data[responsive]=yes', 
 
    error: function(result) { 
 
    // External video is not available, use this one instead: 
 
    $('#14750915864459730').replaceWith('<video width="1920" height="1080" mp4="http://www.mywebsite.com/wp-content/uploads/2016/09/americ.mp4">'); 
 
    }, 
 
    timeout: 2000 // Stops trying after 2 seconds 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="14750915864459730"> 
 
    <script type="text/JavaScript" src="https://www.example.com/embed/dl4ue?data[rnddiv]=14750915864459730&data[responsive]=yes"></script> 
 
</div>

編輯:作爲人Manam注意到,這problably不會因跨來源問題的工作。如果您願意,可以通過調整服務器端CORS配置來解決此問題。

或者,一個僅限於JavaScript的解決方案是使用此模塊:https://github.com/padolsey-archive/jquery.fn/blob/master/cross-domain-ajax/jquery.xdomainajax.js。包括這個腳本將有效解決Cross-Origin問題。

+1

此代碼不起作用因爲jQuery不允許跨來源請求。 –

+0

@ManManam你是對的,謝謝你的注意。由於您的答案已經提供了一個服務器端解決方案,我在我的答案中添加了一個客戶端修補程序,用於那些喜歡 –

1

您可以ping服務器並使用結果查看服務器是否可用。 試試這個:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<script> 
function ping(){ 
    $.ajax({ 
    type: 'GET', 
    dataType: "json", 
    url: "https://www.example.com/embed/dl4ue?data[rnddiv]=14750915864459730&data[responsive]=yes", 
    success: function (responseData, textStatus, jqXHR) { 
     //server is NOT down. So embed your video 
     // Code1 here 
    }, 
    error: function (responseData, textStatus, errorThrown) { 
     alert('POST failed.'); // server is down 
     // Code2 here 
    } 
    }); 
} 
</script> 

編輯:JQuery的不支持跨域AJAX。所以你不能將Ajax移植到另一個域。如果你想crossDomain AJAX許可,您可以使用下面的代碼PHP(如果你的服務器端代碼是PHP):

header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); 
header('Access-Control-Max-Age: 1000'); 
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); 
+0

的人我無法解決XMLHttpRequest無法加載example.com。請求的資源上沒有「Access-Control-Allow-Origin」標題。錯誤 –

+0

當在我的域中使用內部頁面時,此函數總是返回錯誤(發佈失敗)!這是其他問題! –

+0

@nimasp這是我們在答案中提到的跨源問題。您應該添加從這個答案的PHP代碼或從我的答案鏈接的JavaScript模塊來解決這個 –