我想使用ajax读取文本文件并将其转换为数组以填充选择框。问题是,我无法弄清楚为什么Ajax代码不会工作。我每次测试出Chrome的代码,我得到这个错误来自jQuery的:使用Ajax读取csv /文本文件
XMLHttpRequest cannot load file:///C:/filepath.../AttributeCategories.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
这里的HTML页面:
$(document).ready(function(){
$('#btn').click(function(){
$.ajax({
type: "GET",
url: "AttributeCategories.txt",
dataType: "text",
success: function (data) {
processData(data);
}
});
});
function processData(data){
var attrcsv = data.split("\n"); //----------------------------------split the csv into rows
var ctgyList = attrcsv[0].split(","); //----------------------------split the first row into categories
for(var i = ctgyList.length + 1; i > 0; i--){//---------------------trim empty items off the array
if(isNaN(ctgyList[i]) == true){ctgyList.splice(i,1);}
}
$('#sel')[0].options.length = 0;//----------------------------------clear select options
for(var i = 0; i < ctgyList.length; i++){//-------------------------build select from the array
$('#sel').append($('',{value:i + 1,text:ctgyList[i]}));
}
}
});
Click Me! |
所有的文件(HTML和文本文件)在同一个文件夹中。 任何帮助或澄清将是有益的,谢谢。
2016-08-01
Smily
+0
您无法读取本地文件。 –
+0
您必须在(本地)服务器上托管您的代码。 –
+0
如果您想要读取文件,请使用HTML5中的文件读取器API,并且可以针对异步体验执行回调。 –