2016-06-14 105 views
0

我想加载一个文本文件,像下面这样的数组,因此它可以在JavaScript中访问,我怎么能通过ajax调用来访问文本文件?这是文本文件artists.txt加载数组保存到文本文件转换为javascript

["Fally ipupa","Radio & Weasel","P-Square feat. Don Jazzy","Mose Fanfan","Fally ipupa","Mercy Masika","Madilu System","Koffi Olomidé","DaVido","Luciano","Kanda Bongo Man","Franco","Franco","DJ Afrobeat","Oliver Mtukudzi","Sauti Sol","Alikiba","Aryon","Gramps Morgan","Buju Banton","Wailing Souls","Bob Marley & The Wailers","Don Carlos and Gold","Burning Spear","Peter Tosh","George Nooks","Richie Spice","Culture","Sanchez","Terry Linen","Archie Wonder","Jah Cure","Busy Signal","Romain Virgo","Junior Reid","Shaggy","Glen Washington","Ginjah","Lucky Dube","Bushman","Chronixx","Turbulence","Protoje","UB40","Franco","Rich Mavoko","Rose Muhando","Kanda Bongo Man","Diamond"," Davido","Tekno","Daddy Owen","Pépé Kallé","Busy Signal","Franco Et Le T.P. O.K. Jazz","Alice Kamande","Koffi Olomidé","Culture","Alikiba","Papa Wemba","Korede Bello","Madilu System","Reuben Kigame","Gloria Muliro"] 
+0

你可以在问题中加入'js'吗?是文件本地还是远程资源? – guest271314

+0

对于所有投票人来说,这并不能帮助您回答问题,请建议一种方法来改善问题 –

+0

@LouieAlmeda通过遵循提出一个好问题的主要建议之一,其中包括尝试的证据。目前的问题是“我想要一些代码来做这件事”。 – Marty

回答

0

只需直接使用GET请求通过AJAX调用它。

/************************************************************************************************** 
Ajax 
*/ 
    // Set all of these parameters. 
    // type 
    // url 
    // callback 
    // data 


    Pub.ajax = function (config_ajax) { 
     var xhr = new win.XMLHttpRequest(); 

     // post_json 
     if (config_ajax.type === 'post_json') { 
      xhr.open("POST", config_ajax.url, true); 
      xhr.setRequestHeader("Content-type", "application/json"); 
     } 

     // post 
     if (config_ajax.type === 'post') { 
      xhr.open("POST", config_ajax.url, true); 
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     } 

     // get 
     if (config_ajax.type === 'get') { 
      xhr.open('GET', config_ajax.url, true); 
     } 

     // post for form_data 
     if (config_ajax.type === 'multi') { 
      xhr.open("POST", config_ajax.url, true); 

     } 
     xhr.onload = completed; 
     xhr.send(config_ajax.data); 

     function completed() { 
      if (this.status === 200) { 
       config_ajax.callback(xhr.responseText); 
      } else { 
       throw new Error("xhr.status is " + this.status); 
      } 
     } 
     xhr.app_url = config_ajax.url; 
     Priv.createStatusBar(xhr); 

     return xhr; 
    }; 
0

为了使它通过Ajax调用工作,

  1. 将文件重命名为artists.json
  2. 设置MIME类型在你的Web服务器,作为以.json扩展应用/ JSON。这将在大多数网络服务器中设置。
  3. 然后做一个Ajax调用,如果你使用的库如jQuery那是相当平直如下

    URL =我site.com/artists.json;

    $.ajax({ 
        dataType: "json", 
        url: url, 
        data: data, 
        success: success 
    }); 
    

这应该会自动让你获取和阅读你的成功方法的JSON文件。

相关问题