首页 > 语言 > JavaScript > 正文

jQuery实现简单的Ajax调用功能示例

2024-05-06 15:42:24
字体:
来源:转载
供稿:网友

本文实例讲述了jQuery实现简单的Ajax调用功能。分享给大家供大家参考,具体如下:

这里的jQuery调用为CDN地址://cdn.bootcss.com/jquery/3.3.1/jquery.min.js

jQuery确实方便,下面做个简单的Ajax调用:

建立一个简单的html文件:

<!DOCTYPE HTML><html><head><script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script type="text/javascript">  $(function(){    //按钮单击时执行    $("#testAjax").click(function(){       //取Ajax返回结果       //为了简单,这里简单地从文件中读取内容作为返回数据       htmlobj=$.ajax({url:"/Readme.txt",async:false});        //显示Ajax返回结果        $("#myDiv").html(htmlobj.responseText);     });  });</script></head>  <body>    <div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>    <button id="testAjax" type="button">Ajax改变内容</button>  </body></html>

好了,点击按钮就可以看到效果了。

当然,jQuery的Ajax调用可以控制项很多,这里演示了简单的调用。

注意你自己的jquery引用路径。

好吧,做一个调用后台的例子:

<!DOCTYPE HTML><html><head><script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.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;      $("#myDiv").html('<h2>'+html+'</h2>');     });  });</script></head>  <body>    <div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>    <button id="testAjax" type="button">Ajax改变内容</button>  </body></html>

后台test.php文件代码:

<?php  $msg='Hello,'.$_POST['name'].',your age is '.$_POST['age'].'!';  echo $msg;

当然,我们还可以这样来调用Ajax:

<!DOCTYPE HTML><html><head><script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.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){            $("#myDiv").html('<h2>'+data+'</h2>');         }      });     });  });</script></head>  <body>    <div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>    <button id="testAjax" type="button">Ajax改变内容</button>  </body></html>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选