Question

I have a list of names in a text file

example:

user1 = Edwin Test //first line of text file
user2 = Test Edwin //second line of text file

I would like each lines data to be set to a variable:

user1 and user2 //so that after jquery loads I can user $user1 and it will give Edwin Test

Text file will be in the same folder as jquery file.

My code:

$.get('users.txt', function(data) { 
    alert(data);
    var lines = data.split("\n");

    $.each(lines, function() {
       var line=perLine[i].split(' ');
    });
});

When i load the page using mamp locally, I am able to see the contents on the file using the alert but when i type for example (user1) in the console it says that the variable is not set.

Était-ce utile?

La solution

Here's what I think you want:

$.get('users.txt', function(data) { 
    var lines = data.split("\n");

    $.each(lines, function(i) {
       var line = lines[i].split(' = ');
       window[line[0]] = line[1];
    });
});

later on...

console.log(user1); // "Edwin Test"

Autres conseils

var users = {};
var lines = data.split("\n");
$.each(lines, function (key, value) {
    var prep = value.split(" = ");
    users[prep[0]] = prep[1];
});

To output user1 You would call users.user1

JSFiddle

The code adds lots of variables to the global namespace. Also, it invites bugs because $.get is asynchronous and so code that depends on the variables existing needs to be called where shown in the comment to be guaranteed to work. This would be considered bad style by many, but here's how to do it:

$.get('users.txt', function(data) { 
    alert(data);
    var lines = data.split("\n");
    var i,l=lines.length,parts;
    for(i=0;i<l;++i){
        parts = lines[i].split('=');
        if (parts.length == 2){
           try {
              // window is the global object. window['x']=y sets x as a global
              window['$'+parts[0]] = parts[1]; // call the var $something 
           } catch(e) {}; // fail silently when parts are malformed
         }
        // put any code that relies on the variables existing HERE
    }
});

Here's what you might do instead:

Put the data in an object. Pass the object to a function showVars(vars) that contains the next step.

   $.get('users.txt', function(data) { 
        alert(data);
        var lines = data.split("\n");
        var i,l=lines.length,parts, vars = {};
        for(i=0;i<l;++i){
            parts = lines[i].split('=');
            if (parts.length == 2){
               try {
                  vars[parts[0]] = parts[1];
               } catch(e) {}; // fail silently when parts are malformed
             }
            showVars(vars); // put any code that relies on the variables existing HERE
        }
    });

    function showVars(vars){
        // put whatever uses/displays the vars here
    }

Yet another way to make this easier to change the data format. If you can store the data in this format, called JSON:

['Edwin Test','Test Edwin','Someone Else','Bug Tester']

Then the parser is either a one liner array = JSON.parse(jsonString) or sometimes is done for you by jQuery and put in data. JSON can store all kinds of data, and there is support for it in other languages libraries besides Javascript, such as PHP, python, perl, java, etc.

$.get('users.txt', function(data) { 
    alert(data);
    var lines = data.split("\n");

    for(var i = 0 ; i < lines.length; i++){
      var line=lines[i].split(' ');
    });
});

I think you are missing the i in the loop.

I guess you could also do

$.each(lines, function(i) { 
  var line=lines[i].split(' '); 
});

In any event, I would probably recommend that you do this string splitting on the server instead and deliver it to the client in the correct/ready form.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top