0

I am a newbie to javascript and jquery. I try to test my html locally. I can work with code properly as below.

<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("div").load('test1.txt');
  });
});

</script>
</head>
<body>

<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>

</body>
</html>

But, when I put the text 'http://www.w3schools.com/jquery/test1.txt' instead of 'test1.txt', the button cannot work properly. Please help.

Regards,

Tommy

Tommy Liu
  • 239
  • 4
  • 13

2 Answers2

2

You are not allowed to do cross-browser ajax.

With the above code, you can just load files either from the same domain, or from local only, if both your target and code file are at local.

You should do it with the help of server side language, like your javascript communicating some own server file like test.php or test.aspx, and that server side file could be communicating with external websites, like CUrl in PHP.

Though you can still do some cross-browser script or data loading, as shown here -> How do I include a JavaScript file in another JavaScript file?

but it needs some dedicated hacks.

Community
  • 1
  • 1
linuxeasy
  • 6,269
  • 7
  • 33
  • 40
  • If I really need to cross query, what can I do? Thank you. – Tommy Liu Feb 25 '12 at 08:28
  • You should do it with the help of server side language, like your javascript communicating some own server file like test.php or test.aspx, and that server side file could be communicating with external websites, like CUrl in PHP. – linuxeasy Feb 25 '12 at 08:29
  • linuxeasy - But, I cannot find any library and method to get external website by using codeigniter [PHP framework]. Do you have any link for my reference? Thank you. – Tommy Liu Feb 25 '12 at 09:05
  • 1
    a simple way to read a txt file from a different domain is file_get_contents http://www.php.net/manual/en/function.file-get-contents.php alternativley use curl as linuxeasy mentions – clem Feb 25 '12 at 10:07
0

If it is an external file in another domain, try the following :

// Your js

<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    var url='http://www.w3schools.com/jquery/test1.txt';
    $.get('myphppage.php',{url:url},function(data) {
        $('div').html(data);
    });   
  });
});
</script>

// myphpage.php script that displays the content of the external file

<?php
if(isset($_GET['url'])) {
    header("Content-type: text/plain");
    echo file_get_contents(urldecode($_GET['url']));
}
?>
Valky
  • 1,856
  • 3
  • 20
  • 38