两种请求:

执行get请求的格式:

$.get(url,function(data,status){
这里面一般用来处理服务器反馈的数据data,将data响应到页面上
})

字节请求,不带任何参数 :

$.get("url");

需要带上参数的话与平常的get请求参数传递一样。

$.get("url?name=zhangsan&age=18");

执行post请求的格式:

$.post(url,data,function(data,status){
这里面一般用来处理服务器反馈的数据data,将data响应到页面上
},“json”) 注意:执行post请求时一定要带上数据格式"json"这是与get 的区别

直接,请求不带上任何数据:

$.post("url" );

请求,带上数据(以json的格式):

$.post("url" , {name:"xx" , age:99});

其中:
如果想要获取服务器反馈的数据,需要在get里面在加一个参数。 给定一个方法即可。服务器响应后,会执行该方法。
注意,方法里面的参数格式固定, data , status 。
data : 代表服务器响应过来的数据(多半是json和XML格式),
status 代表这次请求的响应状态码(一般不需要这个参数)。

两个例子:

一.模仿百度搜索提示

建立数据库:

编写前端页

<body>
<center><h2>百度</h2><input type="text" id="word" style="width: 600px ; height: 50px  ;font-size: 20px;"><input type="button" value="百度一下"  style="height: 55px ; width: 100px ; "><div id="div01" style="position:relative; left : -54px; width: 600px; height: 200px ; border:  1px solid blue; display: none"></div>
</center></body>

编写servlet(url路径):

public class FindWordServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {//获取前端传过来的wordString word = request.getParameter("word");WordDaoImpl dao = new WordDaoImpl();//得到模糊查询出来的list集合List<Word> words = dao.findWord(word);//存放到request域中request.setAttribute("list",words);//在list.jsp中接受这个list集合request.getRequestDispatcher("list.jsp").forward(request,response);} catch (SQLException e) {e.printStackTrace();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request,response);}
}

编写支撑servlet处理数据的dao和daoImpl,返回一个wordBean的集合

public class WordDaoImpl implements WordDao {@Overridepublic List<Word> findWord(String word) throws SQLException {QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());String sql = "select * from word where word like ?";return runner.query(sql,new BeanListHandler<Word>(Word.class),word+"%");}
}

用于接收集合的list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><table style="width: 100%"><c:forEach items="${list}" var="wordBean"><tr><td>${wordBean.word}</td></tr></c:forEach></table>

最重要的jquery代码:

<script>$(function () {//触发一个键盘谈起事件$("#word").keyup(function () {//如果没有输入,则隐藏div框if($("#word").val() == ""){$("div").hide();}else{//如果有输入,则执行ajax的post请求$.post("FindWordServlet",{word:$("#word").val()},function (data) {// alert(data) data里面是一个html的table$("div").show().html(data)})}})})</script>

二.省市联动

建立数据库

前端页面:

<body>
省份: <select name="province" id ="province"><option value="" >-请选择 -<option value="1" >广东<option value="2" >湖北
</select>
城市:
<select name="city" id="city"><option value="" >-请选择 -
</select>
</body>
</html>

servlet获取前端传过来的pid去dao层处理数据:
其中涉及到两个技术:
1.将集合对象转化为XML对象的格式传给前端(使用到xStream封装好的的依赖包,用xStream.toXML()方法)
2.将集合对象转化为json对象的格式传给前端(使用json封装好的依赖包,用JSONArray.fromObject(list).toString()方法)

public class CityServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {//1获取前端传过来的pid,转化为bean中的int类型int pid = Integer.parseInt(request.getParameter("pid"));CityDaoImpl cityDao = new CityDaoImpl();//2.去dao数据处理层从数据库获取想要的city集合List<CityBean> list = cityDao.findCityByPid(pid);/*//利用xstream讲list对象转化为xml的字符串XStream xStream = new XStream();//想把pid做成属性xStream.useAttributeFor(CityBean.class, "pid");//设置别名xStream.alias("city", CityBean.class);String xml = xStream.toXML(list);*///3.将list对象转化为json对象数组JSONArray jsonArray = JSONArray.fromObject(list);String json = jsonArray.toString();
//            System.out.println(json);response.setContentType("text/html;charset=utf-8");response.getWriter().write(json);//响应给前端页面的数据} catch (SQLException e) {e.printStackTrace();}}

dao处理数据:

public class CityDaoImpl implements CityDao {@Overridepublic List<CityBean> findCityByPid(int pid) throws SQLException {QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());String sql = "select * from city where pid=?";return runner.query(sql,new BeanListHandler<CityBean>(CityBean.class),pid);}
}

前端jq-ajax获取到servlet响应回来的json对象(也就是回调函数里的参数data):

        $(function () {//select一旦发生改变,就通过value值(也就是pid)去servlet中找到该省份对应的城市集合$("#province").change(function () {//清空select下的子元素option$("#city").empty()//发送一个post请求,把value的值(也就是pid)带到servlet中,servlet响应回来一个data(xml,json)$.post("CityServlet",{pid:$(this).val()},function (data) {/*//处理xml类型的数据$(data).find("city").each(function () {var id = $(this).children("id").text();var cname = $(this).children("cname").text();$("#city").append("<option value='"+id+"'>"+cname);})*///处理json类型的数据$(data).each(function (i,n) {// alert(n.cname)$("#city").append("<option value='"+i+"'>"+n.cname);})},"json")})})

服务器响应回来的两种数据格式:

1.json

 [{"cname":"深圳","id":1,"pid":1},{"cname":"广州","id":2,"pid":1},{"cname":"惠州","id":3,"pid":1},{"cname":"东莞","id":4,"pid":1}]

2.xml格式:

<list><city pid="1"><id>1</id><cname>深圳</cname></city><city pid="1"><id>2</id><cname>广州</cname></city><city pid="1"><id>3</id><cname>惠州</cname></city><city pid="1"><id>4</id><cname>东莞</cname></city>
</list>

JQuery方式执行ajax请求相关推荐

  1. 关于JQuery中的ajax请求或者post请求的回调方法中的操作执行或者变量修改没反映的问题...

    前段时间做一个项目,而项目中所有的请求都要用jquery 中的ajax请求或者post请求,但是开始处理一些简单操作还好,但是自己写了一些验证就出现问题了,比如表单提交的时候,要验证帐号的唯一性,所以 ...

  2. Ajax和JSON-学习笔记02【JQuery方式实现Ajax】

    Java后端 学习路线 笔记汇总表[黑马程序员] Ajax和JSON-学习笔记01[原生JS方式实现Ajax] Ajax和JSON-学习笔记02[JQuery方式实现Ajax] Ajax和JSON-学 ...

  3. ajax. jquery. 异步,jQuery之异步Ajax请求使用

    $.ajax({type:'',data:'',async:''...}) 参数: 1.cache: true缓存页面 false 不缓存页面 (默认: true,dataType为script和js ...

  4. jQuery中终止Ajax请求

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. IE浏览器中访问jsp页面,页面不执行ajax请求,后台控制台报错

    问题描述:IE浏览器中访问jsp页面,页面不执行ajax请求,后台控制台报错:java.lang.IllegalArgumentException: Invalid character found i ...

  6. jQuery学习之四---Ajax请求

    1.$.ajax(url,[settings]) jQuery版的Ajax:是对原生XMLHttpRequest对象的封装,同时也省去了很多麻烦 当然前提是,你需要有一份JQ文件,可以自己去官网上去下 ...

  7. 使用axios方式实现Ajax请求

    项目已开源至gitee:https://gitee.com/guo-qianliang/es6-vue-node.js 项目已开源至github:https://github.com/Guoqianl ...

  8. Jquery中的ajax请求($.ajax())参数请求详解

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  9. PHP和ajax请求_「jQuery+PHP」ajax请求以及接口PHP响应教程

    各位客官好,平时我们在开发时,不可避免的会用到Ajax与后台做数据交互,那么今天小编今天就给各位没有用过Ajax的客官以及准备接触的客官讲解一下,并且小编会为大家讲一下请求时的loading层等待以及 ...

最新文章

  1. python celery
  2. Linux常用指令---find | locate(查找)
  3. 服务器性能优化的正确姿势
  4. 设计师学习HTML/CSS之路-01
  5. 线段树练习——区间合并
  6. ABAP常用function 收藏
  7. 【JUnit 报错】 method initializationerror not found:JUnit4单元测试报错问题
  8. CISCO 防火墙建立穿越NAT的×××几种解决方法
  9. 单片机 驱动 标签打印机tsc_指令打印与驱动打印随笔
  10. nyoj 86 找球号(一)
  11. PHP-dede学习:common.ini.php文件
  12. 学术论文的定义、特点、写作方法以及写作格式
  13. linux stm32 虚拟串口驱动安装,stm32usb虚拟串口驱动
  14. html5游戏cps,15字讲清CPC、CPM、CPA、CPS、CPL…没节操了
  15. 实例化Servlet类异常404、500错误-解决方法
  16. 数学板块学习之FWT
  17. 华为linux系统安装包,一、Linux系统安装
  18. 用python制作一张简单的节日贺卡
  19. 搭载“鸿蒙”的华为Watch 3,是智能手表的标准答案吗?
  20. left join 和 left outer join (可解决多个表left join的问题)

热门文章

  1. Python编程基础:第五节 用户输入User Input
  2. 淘宝大数据之路【转】
  3. Lambda架构在有赞广告平台的应用与演进
  4. spring AOP策略模式使用
  5. 【未来可能用到】关于模型的100个问答-part2
  6. 元宇宙iwemeta:互联网行业年底清算,税收优惠门槛抬高,阿里巴巴多交41亿税款
  7. 中台创业潮起,你中台创业了吗?
  8. 图文详解】Chrome中安装JsonView插件
  9. 如何向新手程序员介绍编程?
  10. Debug Assert Failed 怎么办?