Say I have this txt file, and inside it is:
title(Here is the title that gets inserted into the title element) body(Here is the body text that gets inserted into the body element)
and I want jquery to insert the title into the title element and the body into the body element. Is this possible, or do I need to use separate txt files for each content? I am new to jquery so this isn't very obvious to me.
I have this code so far:
$(function(){
$( "#title" ).load( "content/home.txt" );
$( "#body" ).load( "content/home.txt" );
});
If this was difficult to understand I hope this code would better explain it.
-
Javascript does not have the ability to read from your filesystem without user interaction. You would have to provide a file selection dialog, then the user would have to select the file to open.James McDonnell– James McDonnell2015年07月08日 23:41:49 +00:00Commented Jul 8, 2015 at 23:41
-
Checkout this link sitepoint.com/jquery-read-text-file Once you get the file loaded, then you can apply it to your DOM.KJYe.Name– KJYe.Name2015年07月08日 23:42:52 +00:00Commented Jul 8, 2015 at 23:42
-
If this is a content on your server use JSON objects and Ajax approach.Will be more efficientMateutek– Mateutek2015年07月08日 23:43:32 +00:00Commented Jul 8, 2015 at 23:43
-
@JamesMcDonnell This is inside the ftp along with the website itself, and I've tested it and it reads the txt file no problem.Sebastian Olsen– Sebastian Olsen2015年07月08日 23:44:14 +00:00Commented Jul 8, 2015 at 23:44
-
Ah I was mistaken to think that you wanted to read it from the users computer, not the web server.James McDonnell– James McDonnell2015年07月08日 23:46:08 +00:00Commented Jul 8, 2015 at 23:46
3 Answers 3
Simple:
Have a file (doc.json) with contents:
{
"title" : "some title",
"body" : "some body text"
}
And on your page
$.getJSON( "doc.json", function( data ) {
$("#title").text(data.title);
$("#body").text(data.body);
});
1 Comment
Your textfile could have the title, body separated by a delimiter. So for example your .txt file would look like this:
// = is the delimiter
title=body
Jquery will read the file contents into a variable (using $.get). We separate the title and body into an array by using the split() function:
function ReadFile() {
$.get("test.txt", function (response) {
var arrStr = response.split("=");
$('#txtbox1').val(arrStr[0]); //title
$('#txtbox2').val(arrStr[1]); //body
});
}
Comments
Change your home.txt file to an html file, and have it contain something like this:
<html>
<head>
<title>Foo!</title>
</head>
<body>Bar!</body>
</html>
Then change your code to this
$(function(){
$( "#title" ).load( "content/home.html title" );
$( "#body" ).load( "content/home.html body" );
});
Alternatively you could store your file as a JSON object, load it with $.ajax, and then use those values. This would make it so your text file doesn't have to be valid html.
Either way will probably work. However this is a solution that is probably better suited to a server side language.