如何将C#变量设置为JavaScript数组变量,即数组。
choices
之后是数组变量。m_lines
是c#数组变量。
<script type="text/javascript">
$(document).ready(function () {
term = term.toLowerCase();
var choices = [];
choices = '<%= m_lines %>';
//var choices = ['aaaab', 'ActionScript', 'AppleScript', 'Asp', 'Assembly', 'BASIC', 'Batch', 'C', 'C++', 'CSS', 'Clojure', 'COBOL', 'ColdFusion', 'Erlang', 'Fortran', 'Groovy', 'Haskell', 'HTML', 'Java', 'JavaScript', 'Lisp', 'Perl', 'PHP', 'PowerShell', 'Python', 'Ruby', 'Scala', 'Scheme', 'SQL', 'TeX', 'XML'];
});
</script>
我的实际要求是读取一个大文本文件(大小约3 MB)并将其分配给JavaScript数组变量。我无法从客户端读取文件并将其分配给JavaScript变量,因此在服务器端读取并尝试将其分配给客户端变量。 每行文件都用作数组项。
答案 0 :(得分:1)
试试这个 -
var choices = <% if (m_lines!= null) {Response.Write(m_lines.ToString());}%>
答案 1 :(得分:1)
在对该问题的评论中,您将m_lines
定义为数组。这里的一种方法可能是简单地将该数组序列化为JSON:
choices = <%= JsonConvert.SerializeObject(m_lines) %>;
这当然是使用the Newtonsoft JSON.NET library。您也可以使用JavaScriptSerializer
(在System.Web.Script.Serialization
中)。
答案 2 :(得分:0)
从您的示例中获取脚本,这可能是:
<script type="text/javascript">
$(document).ready(function () {
term = term.toLowerCase();
var choices = [];
choices = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(m_lines) %>;
//var choices = ['aaaab', 'ActionScript', 'AppleScript', 'Asp', 'Assembly', 'BASIC', 'Batch', 'C', 'C++', 'CSS', 'Clojure', 'COBOL', 'ColdFusion', 'Erlang', 'Fortran', 'Groovy', 'Haskell', 'HTML', 'Java', 'JavaScript', 'Lisp', 'Perl', 'PHP', 'PowerShell', 'Python', 'Ruby', 'Scala', 'Scheme', 'SQL', 'TeX', 'XML'];
});
或者,如果这是一个逗号分隔的文本文件并且在客户端,您可以使用javascript读取它,例如:
// <input name="myfile" id="myfile" type="file" />
$("#myfile").on('change', function () {
var file = this.files[0];
// Some validations
console.log(file.name);
console.log(file.size)
var FileReader = new window.FileReader();
reader.onload = function (event) {
// The file's text will be in event.target.result
//console.log(event.target.result)
var fileContentArray = event.target.result.split(/\r\n|\r|\n/g); // split by newlines
// Use the file content in fileContentArray
};
reader.readAsText(file);
});
请参阅:https://developer.mozilla.org/en-US/docs/Web/API/FileReader