建立一个简单的html文件:
<!doctype html><html><head><script type="text/javascript" src="public/js/jquery-easyui-1.3.1/jquery-1.8.2.min.js"></script><script type="text/javascript"> $(function(){ //按钮单击时执行 $(#testajax).click(function(){ //取ajax返回结果 //为了简单,这里简单地从文件中读取内容作为返回数据 htmlobj=$.ajax({url:/readme.txt,async:false}); //显示ajax返回结果 $(#myp).html(htmlobj.responsetext); }); });</script> </head> <body> <p id="myp"><h2>通过 ajax 改变文本</h2></p> <button id="testajax" type="button">ajax改变内容</button> </body></html>
好了,点击按钮就可以看到效果了。
当然,jquery的ajax调用可以控制项很多,这里演示了简单的调用。
注意你自己的jquery引用路径。
好吧,做一个调用后台的例子:
<!doctype html><html><head><script type="text/javascript" src="public/js/jquery-easyui-1.3.1/jquery-1.8.2.min.js"></script><script type="text/javascript"> $(function(){ //按钮单击时执行 $(#testajax).click(function(){ //ajax调用处理 var html = $.ajax({ type: post, url: test.php, data: name=garfield&age=18, async: false }).responsetext; $(#myp).html('<h2>'+html+'</h2>'); }); });</script> </head> <body> <p id="myp"><h2>通过 ajax 改变文本</h2></p> <button id="testajax" type="button">ajax改变内容</button> </body></html>
后台代码:
现在已经可以从后台来获取数据了!
当然,我们还可以这样来调用ajax:
<!doctype html><html><head><script type="text/javascript" src="public/js/jquery-easyui-1.3.1/jquery-1.8.2.min.js"></script><script type="text/javascript"> $(function(){ //按钮单击时执行 $(#testajax).click(function(){ //ajax调用处理 $.ajax({ type: post, url: test.php, data: name=garfield&age=18, success: function(data){ $(#myp).html('<h2>'+data+'</h2>'); } }); }); });</script> </head> <body> <p id="myp"><h2>通过 ajax 改变文本</h2></p> <button id="testajax" type="button">ajax改变内容</button> </body></html>
注意,
success: function(data)
中的data参数可以改为别的名称,比如success: function(msg),msg(data)为返回的数据。 此处为回调函数的参数,而非
data: name=garfield&age=18
中的ajax调用中的data参数。
以上就是jquery简单的ajax调用示例的详细内容。
