分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

ajax 异步请求,json前台后台交互

发布时间:2023-09-06 01:42责任编辑:熊小新关键词:jsjson异步请求

直接上例子!

第一例:

1.导入json的相关jar包

2.后台servlet代码

public class ajaxtest extends HttpServlet { ???public void doGet(HttpServletRequest request, HttpServletResponse response) ???????????throws ServletException, IOException { ???????request.setCharacterEncoding("utf-8"); ???????response.setContentType("text/html;charset=utf-8");
     //上面是处理乱码的 ???????String[] str = {"张三","李四","王五"}; ?//最普通的json数组结构 ???????JSONArray json = JSONArray.fromObject(str); ?//string转json结构 ???????PrintWriter out = response.getWriter();   ???????out.print(json); ???//response 将json输出到客户端。
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
?}
}

前端jsp页面

<script type="text/javascript" ???src="http://libs.cdnjs.net/jquery/3.2.1/jquery.js"></script><script type="text/javascript">$(document).ready(function(){ ?$("#b01").click(function(){ ?????$.getJSON("${pageContext.request.contextPath}/ajaxtest",function(result){ ?????????$.each(result,function(i,field){ ?????????????$("#myDiv").append(field+":"); ?????????}); ?????}); ?}); ?});</script></head><body><div id="myDiv"><h2>通过 AJAX 改变文本</h2></div><button id="b01" type="button">改变内容</button>

点击按钮的结果:张三:李四:王五。

----------------------------------------------------------

第二例

ajax 异步请求,json前台后台交互

原文地址:https://www.cnblogs.com/pxffly/p/8440068.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved