2
テキストファイルを読み込んで選択ボックスに入力するためにajaxを使用して配列に変換したいと考えています。問題は、なぜajaxコードが機能しないのかわかりません。私はChromeでコードをテストするたびに、私はjQueryのからこのエラーを取得する:Ajaxを使用してcsv/textファイルを読み取る
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(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($('<option>',{value:i + 1,text:ctgyList[i]}));
}
}
});
</script>
</head>
<body>
<div>
<table>
<tr><td><button id="btn">Click Me!</button></td></tr>
<tr><td><select id="sel"></select></td></tr>
</table>
</div>
</body>
すべてのファイル(HTMLやテキストファイル:
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ページがあります)は同じフォルダにあります。 助けや説明が役に立ちます。ありがとうございます。
ローカルファイルを読み取ることができません。 – gcampbell
(ローカル)サーバーでコードをホストする必要があります。 – Wolfgang
ファイルを読みたい場合は、HTML5のファイルリーダーAPIを利用してください。非同期の経験のためにコールバックを行うことができます。 – ODelibalta