$.get() $.post() $.ajax() 发送 ajax请求

这三种方法都是jQuery中规定的Ajax方法中一种与服务器交换数据的请求类型。

  1. $.get() 使用

使用方式: $.get(url, [data], [callback], [type])

URL为请求地址(必填),callback为回调函数(可填)
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text,

样例:

	$.get('http://127.0.0.1:8000/jquery-server', function (data) {
	                $('.a').html(data.name);
	                console.log(data);
	            }, 'json')
  1. $.post() 使用

使用方式: $.post(url, [data], [callback], [type])

URL为请求地址(必填)
callback为回调函数(可填)
data为请求发送的数据(可填)
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text,

样例 :

	$.post('http://127.0.0.1:8000/jquery-server', function (data) {
	                $('.a').html(data.name);
	                console.log(data);
	            }, 'json')
  1. $.ajax() 使用

该方法可以执行精确的需求控制,通常用于其他方式不能完成的请求

样例

	 $.ajax({
	                // 请求类型
	                type: 'GET',
	                // 请求url
	                url: 'http://127.0.0.1:8000/jquery-server',
	                // 响应体结果
	                dataType: 'json',
	                // 超时设置
	                timeout: 2000,
	                // 成功回调
	                success: function (data) {
	                    $('.a').html(data.name);
	                    console.log(data);
	                },
	                // 失败回调
	                error: function () {
	                    console.log('出错啦 !!');
	                },
	            });
  1. 以上三种实现ajax请求都基于下面 server.js代码 app.all 可以接受(get ,post请求)
	//1.引入express
	const { request, response } = require('express');
	const express = require('express');
	//2.创建应用对象
	const app = express();
	// 3.创建路由规则
	app.all('/jquery-server', (request, response) => {
	    // 设置响应头 设置允许跨域
	    response.setHeader('Access-Control-Allow-Origin', '*');
	    // 用 Cors 来解决跨域问题
	    response.setHeader('Access-Control-Allow-Headers', '*');
	    response.setHeader('Access-Control-Allow-Method', '*')
	    // 设置响应体 
	    let data = {
	        name: '方敬'
	    }
	    response.send(JSON.stringify(data));
	
	
	});
	//4.监听端口启动服务
	app.listen(8000, () => {
	    console.log("服务已经启动,8000端口....");
	});

5.打开浏览器 输入 :http://127.0.0.1:8000/jquery-server 在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值