【问题标题】:Jquery load text into div - multiple values/divsJquery 将文本加载到 div - 多个值/div
【发布时间】:2016-08-23 20:09:59
【问题描述】:

我有一个包含多行的文本文件,需要将其加载到不同的 div 中。文本文件如下所示:

Jon
Doe
25

Jane
Doe
37

Foo
Bar
18

如何加载此文件并填充以下 div?

<input id="firstname" type="text"></input>
<input id="lastname" type="text"></input>
<input id="age" type="text"></input>

<input id="firstname1" type="text"></input>
<input id="lastname1" type="text"></input>
<input id="age1" type="text"></input>

<input id="firstname2" type="text"></input>
<input id="lastname2" type="text"></input>
<input id="age2" type="text"></input>

加载div

   $(".myDiv").load("myFile.txt");  

使用 json 或 csv 也不是不可能的......

【问题讨论】:

    标签: javascript jquery ajax text load


    【解决方案1】:
    var strings = fileTextBlob.split('\n');
    $(".myDiv").children("input").each(function(index, inputEl){
        var tmpStr = strings.shift();
        //Catch empty lines. Could add more logic to catch strings of all spaces, etc.
        while(!tmpStr && typeof(tmpStr) !== "undefined"){
            tmpStr = strings.shift();
        }
        $(inputEl).text(tmpStr);
    })
    

    【讨论】:

    • 这很接近 - 你能解释一下 fileTextBlob 部分吗?
    • 当然。 fileTextBlob 代表文本文件中的原始数据。在网页上,您可以通过两种主要方式获取此数据:允许用户打开文件 (cs.tut.fi/~jkorpela/forms/file.html),或者,如果您的数据在您的服务器上,则发出 Ajax 请求以获取数据: var fileTextBlob; $.get("myfile.txt", function(responseData){ fileTextBlob = responseData; //现在你有了数据,你可以更新你的页面 doUpdate(); }) 在一个完美的世界里,你的服务器可以发送 JSON您可以改为解析 (api.jquery.com/jquery.getjson)
    【解决方案2】:

    将数据排列为对象的 json 数组

    var data = [
      {
        "firstname": "Jon",
        "lastname": "Doe",
        "age": 25
        },  {
          "firstname": "Jone",
          "lastname": "Doee",
          "age": 21
        }
      ]
    

    然后使用 JQuery 你可以构建 div

    var body = $('body');
    $.each(data, function(index, value){
      body.append($('<input type="text" id="firstname' + index + '" >').text(value.firstname));
      body.append($('<input type="text" id="lastname' + index + '" >').text(value.lastname));
      body.append($('<input type="text" id="age' + index + '" >').text(value.age));
    }
    

    编辑 - 你可以使用getJSON来加载json文件

    $.getJSON( "ajax/test.json", function( data ) {
      var items = [];
      $.each( data, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val + "</li>" );
      });
    
      $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
      }).appendTo( "body" );
    });
    

    【讨论】:

    • 谢谢 - 这可以工作。我仍然调用外部文件很重要。你是说我将我的 txt 文件构建为 json 文件并使用 $('.myDiv').load ('myfile.json'); ?
    猜你喜欢
    • 2012-12-27
    • 2016-06-18
    • 2012-06-23
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多