jQuery - AJAX get() 和 post() 方法

一.两种在客户端和服务器端进行请求-响应的常用方法是:GET 和 POST。

  • GET - 从指定的资源请求数据
  • POST - 向指定的资源提交要处理的数据

  GET 基本上用于从服务器获得(取回)数据。注释:GET 方法可能返回缓存数据。

  POST 也可用于从服务器获取数据。不过,POST 方法不会缓存数据,并且常用于连同请求一起发送数据。

二.使用方法

1.引入jquery

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

2.创建两个按钮,一个使用GET 请求,另一个使用POST请求

  <button id="getButton" type="button" class="layui-btn"> $.get</button> 
  <br /><br />
  <button id="postButton" type="button" class="layui-btn"> $.post</button> 

如图:

         

3.域名单独提取出来方便用

var url='http://localhost/'

4. GET 请求 

url上面定义的域名 

url+"chatRoom/php/get.php"   GET请求接口

function(res){  console.log(res)  }   请求回调

$("#getButton").click(function(){
		$.get(url+"chatRoom/php/get.php",function(res){
		console.log(res)
	 });
  });

php代码:

<?php
echo 'get请求,个从PHP文件中读取的数据。';
?>

 点击按钮返回数据如图:

5.POST请求

url上面定义的域名 

url+"chatRoom/php/get.php"    POST请求接口

data 请求时传的参数

function(res){  console.log(res)  }   请求回调

	$("#postButton").click(function() {
			let data = {
				title: "$.post() 方法通过 HTTP POST 请求向服务器提交数据。",
			}
			$.post(url + "chatRoom/php/post.php", data,
				function(res) {
					console.log(res)
				});
		});

PHP代码:

<?php

$title = isset($_POST['title']) ? htmlspecialchars($_POST['title']) : '';
echo $title;

 点击按钮返回数据如图:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值