Home > Web Front-end > JS Tutorial > body text

jQuery中ajax - get() 方法实例详解

高洛峰
Release: 2016-12-28 14:49:18
original
1170 people have browsed it

在jquery中使用get,post和ajax方法给服务器端传递数据,下面通过本文继续学习jQuery中ajax - get() 方法,具体介绍请看下文。

实例

使用 AJAX 的 GET 请求来改变 div 元素的文本:

$("button").click(function(){
 $.get("demo_ajax_load.txt", function(result){
 $("div").html(result);
 });
});
Copy after login

亲自试一试

定义和用法

get() 方法通过远程 HTTP GET 请求载入信息。

这是一个简单的 GET 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。

语法

$(selector).get(url,data,success(response,status,xhr),dataType)
Copy after login

jQuery中ajax - get() 方法实例详解

详细说明

该函数是简写的 Ajax 函数,等价于:

$.ajax({
 url: url,
 data: data,
 success: success,
 dataType: dataType
});
Copy after login

根据响应的不同的 MIME 类型,传递给 success 回调函数的返回数据也有所不同,这些数据可以是 XML root 元素、文本字符串、JavaScript 文件或者 JSON 对象。也可向 success 回调函数传递响应的文本状态。

对于 jQuery 1.4,也可以向 success 回调函数传递 XMLHttpRequest 对象。

示例

请求 test.php 网页,忽略返回值:

$.get("test.php");

更多示例

例子 1

请求 test.php 网页,传送2个参数,忽略返回值:

$.get("test.php", { name: "John", time: "2pm" } );
Copy after login

例子 2

显示 test.php 返回值(HTML 或 XML,取决于返回值):

$.get("test.php", function(data){
 alert("Data Loaded: " + data);
});
Copy after login

例子 3

显示 test.cgi 返回值(HTML 或 XML,取决于返回值),添加一组请求参数:

$.get("test.cgi", { name: "John", time: "2pm" },
 function(data){
 alert("Data Loaded: " + data);
 });
Copy after login

jquery ajax 的 $.get()用法详解

js文件

$(document).ready(function(){
 $("form").submit(function(event) {event.preventDefault()})//取消submit的默认行为
 $("form input[type='submit']").click(function(){
 var url = $('form').attr('action'); // 取Form中要提交的链接
 var param = {}; // 组装发送参数
 param['name'] = $('form input[name=name]').val();
 param['age'] = $('form input[name=age]').val();
 $.get(url, param, function(dom) { $('div.get').append(dom) }) ; // 发送并显示返回内容
 });
})
Copy after login

html文件

Name: Age:
这是ajax的get方法
Copy after login

php文件

error_reporting(0);
 if($_GET["name"]=="kitty")
{
 $name= "you are the lucky";
}
else
$name=$_GET["name"];
$age=$_GET["age"];
echo "
".$name." ".$age."
";
Copy after login

以上介绍就是本文给大家分享的jQuery中ajax - get() 方法实例详解,希望大家喜欢。

更多jQuery中ajax - get() 方法实例详解相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!