<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>使用get()方法以GET方式从服务器获取数据</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="divtest">
<div class="title">
<span class="fl">我的个人资料</span>
<span class="fr">
<input id="btnShow" type="button" value="加载" />
</span>
</div>
<ul></ul>
</div>
<script type="text/javascript">
$(function () {
$("#btnShow").bind("click", function () {
var $this = $(this);
$.get("http://www.imooc.com/data/info_f.php",function(data) {
$this.attr("disabled", "true");
$("ul").append("<li>我的名字叫:" + data.name + "</li>");
$("ul").append("<li>男朋友对我说:" + data.say + "</li>");
}, "json");
})
});
</script>
</body>
</html>
这代码在浏览器运行是没问题,但是复制到自己的编辑器sublime中再拖到浏览器就不行。是不是这ajax要本地配置服务器啊?load、get,getJSON等方法都这种情况,刚接触这ajax,之前的javascript和jquery都挺好的,求指导
运行效果,怎么点击“加载”都不行。哎,这ajax要怎么学啊,我又没服务器,能在自己的电脑端设置吗?
你在本地搭建一个静态文件服务器来访问这个html文件,点击加载时会到http://www.imooc.com/data/info_f.php加载数据,但是你如果从控制台里看,会有这个错误,这叫跨域。
XMLHttpRequest cannot load http://www.imooc.com/data/info_f.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:12346' is therefore not allowed access.
ajax是用来异步加载用的,可以进行前端和后端之间的数据交换。如果你想实现ajax的功能的话,需要配置本地的服务器,对于初学者,可以直接下一个集成环境。如果你是windows系统可以下载wamp server,xampp等。mac系统的话也有xampp可以下载。再配合后端语言,则能实现ajax的功能!有什么问题可以再问我~
你复制到本地不能运行是因为你示例中的 http://www.imooc.com/data/info_f.php 和你当前域名不在一个域下,这叫跨域,是不允许的。
但我要再说一遍,如果只是为了测试,就不需要配置服务器端环境,用 .json 模拟就可以:
server.json:
{
'name': 'foo',
'say': 'fuck you every day'
}
Javascript:
$(function () {
$("#btnShow").bind("click", function () {
var $this = $(this);
$.getJSON('/server.json',function(data) {
$this.attr("disabled", "true");
$("ul").append("<li>我的名字叫:" + data.name + "</li>");
$("ul").append("<li>男朋友对我说:" + data.say + "</li>");
});
})
});
ajax要访问外部文件或者url,所以肯定要搭建本地静态服务器。