how to display a .txt file in jquery

半世苍凉 提交于 2019-12-11 10:01:24

问题


I have a textarea and this javascript code It should work but dosen't is there something wrong? If so, what is it?

$('#text').load("http://hokuco.com/test/xe7/user.txt");
<form action="formcode.php" method="POST">
<textarea name='field2' placeholder='Code here' rows ="40" cols="40" id ="text"></textarea>
<br />
<input type="submit" name="submit" value="Save">
</form>

here is my php file if curious:

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
    $ret = file_put_contents('code.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}
?>

回答1:


Due to browser security restrictions, most Ajax requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

I'm assuming the .txt file is not on the same server/domain as the HTML file that is trying to load it? If you are, then you should use a relative URL, i.e.:

$('#text').load("xe7/user.txt");

Please refer to: Loading cross domain endpoint with jQuery AJAX




回答2:


Does this work?

jQuery

$(function(){


  $.ajax({
    url : "http://hokuco.com/test/xe7/user.txt",
    dataType: "text",
    success : function (data) {
      $("#text").html(data);
    }
  });


});

HTML

<div id="text"></div>



回答3:


As other users have said, you are violating the same origin policy. If you are using PHP you could echo that into your textarea.

Something along the lines of:

<textarea id="text">
    <?php 
        $text = file_get_contents('http://hokuco.com/test/xe7/user.txt');
        echo $text;
    ?>
</textarea>



回答4:


If the above code is all there is (as you state in your comment to your question), and you have included jQuery, then mere refreshing of the page won't give you the result. As your HTML code is below this jQuery call, the DOM is not ready yet when the function is called. Therefore you need to call this function when the document is ready, according to the rule that all jQuery calls that relate to DOM elements should be made this way:

$(document).ready(function(){
    $('#text').load("test/xe7/user.txt");
});


来源:https://stackoverflow.com/questions/35157500/how-to-display-a-txt-file-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!