我是javascript和jquery的新手。我尝试在本地测试我的HTML。我可以正确使用代码,如下所示。
<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>
但是,当我将文本“http://www.w3schools.com/jquery/test1.txt”改为“test1.txt”时,该按钮无法正常工作。请帮忙。
此致
托米
答案 0 :(得分:2)
您不能进行跨浏览器的Ajax。
使用上面的代码,如果你的目标和代码文件都在本地,你可以只从同一个域加载文件,或者只从本地加载文件。
您应该在服务器端语言的帮助下执行此操作,例如javascript
通信某些自己的服务器文件,如test.php
或test.aspx
,并且该服务器端文件可能正在与外部通信网站,例如CUrl
中的PHP
。
虽然您仍然可以执行一些跨浏览器脚本或数据加载,如此处所示 - &gt; How do I include a JavaScript file in another JavaScript file?
但它需要一些专门的黑客攻击。
答案 1 :(得分:0)
如果是其他域中的外部文件,请尝试以下操作:
//你的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脚本,显示外部文件的内容
<?php
if(isset($_GET['url'])) {
header("Content-type: text/plain");
echo file_get_contents(urldecode($_GET['url']));
}
?>