使用$ .get()从外部源加载内容的后备

时间:2016-05-20 07:42:07

标签: jquery ajax get

您好我需要一些简单的ajax请求函数的帮助。它实际上工作正常,但我需要实现一个后备,以防无法从主源加载文件(.txt),然后我想从后备Dropbox文件夹加载它们。

用户点击id =“filename”的元素,url hash用#filename更新,然后我获取哈希并发出请求从外部源加载文件,如somedomain.com/folder/filename.txt (它也可以在没有click事件的情况下通过将哈希添加到实际url来工作,因为我在加载时触发.hashchange)

这是我的代码:

// get ID from clicked element

$(".info").click(function() {
        window.location.hash = $(this).attr("id");
        event.preventDefault();
});

// bind to hashchange (to be able to load request from URL hash)

$(window).bind('hashchange', function() {

        // Get hash and store in variable
        var myclass;
        $myclass = window.location.hash.substring(1);

        // construct file url from source path + filename
        $source = 'http://www.somedomain.de/folder/' + $myclass + '.txt';

        // alternative source as fallback
        $source_alt = 'https://dl.dropboxusercontent.com/someDropboxFolder/' + $myclass + '.txt';

        // load contents from .txt file and replace html of "#container"
        $.get($source, function(data) {$("#container").html(data);}, 'text');
        // --> IF THIS FAILS I WANT TO MAKE A CALL TO LOAD FROM ALTERNATIVE SOURCE (source_alt)

});   

$(window).trigger('hashchange');

我尝试添加.fail()但是这对请求不起作用但是这不起作用“.fail()不是函数”...

感谢您的任何建议!

2 个答案:

答案 0 :(得分:1)

使用完整语法:

$.ajax({
    method: 'GET',
    url: // your URL,
    data: // your data if needed,
    success: function (result) { ... }, // your action on success
    error: function (jqXHR, textStatus, errorThrown) { ... } // your action on error
});

您可以检查请求期间发生的错误,然后根据它修改逻辑

答案 1 :(得分:0)

您将错误地捕获它并从其他资源加载数据。

var failed_resource = false;
var jqxhr = $.get( "example.php", function() {
      alert( "success" );
    })
      .done(function() {
        alert( "second success" );
      })
      .fail(function() {
         failed_resource = true; 
        alert( "error loading resource. Load data from another resource.." );
      })
      .always(function() {
        alert( "finished request." );
        if(failed_resource == true) {
          loadDataFromAnotherRes();
          }
      });
function loadDataFromAnotherRes() {
  // your code here
  alert('Loading data from another resource..');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>