通过json发送和接受数据,数据以json的格式在服务器端和前台进行传递,什么是json数据?这里就不进行详细阐述,轻自行百度解决。

在html5 中利用ajax 异步请求时,会遇到跨域的问题,如果域名不一致、ip地址不一致,端口不一致都会导致跨域请求不成功。

为了解决这个问题,需要在前台和后台均设置相关的属性进行跨域请求。

现在展示服务器端的代码:

自己封装的过滤器:

package utils;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CrossDomainFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse res = (HttpServletResponse) resp;
// 这里最好不要写通配符,如果允许多个域请求数据的话,可以直接用逗号隔开:"http://www.baidu.com,http://google.com"
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With");
//res.setHeader("Access-Control-Allow-Credentials","false");
chain.doFilter(req, resp);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
} 将字符串转换为json数据格式的工具类:
package utils; import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; public class JsonUtil {
private static Log log = LogFactory.getLog(JsonUtil.class); public static String object2json(Object obj) {
StringBuilder json = new StringBuilder();
if (obj == null) {
json.append("\"\"");
} else if (obj instanceof String || obj instanceof Integer || obj instanceof Float
|| obj instanceof Boolean || obj instanceof Short || obj instanceof Double
|| obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger
|| obj instanceof Byte) {
json.append("\"").append(string2json(obj.toString())).append("\"");
} else if (obj instanceof Object[]) {
json.append(array2json((Object[]) obj));
} else if (obj instanceof List) {
json.append(list2json((List<?>) obj));
} else if (obj instanceof Map) {
json.append(map2json((Map<?, ?>) obj));
} else if (obj instanceof Set) {
json.append(set2json((Set<?>) obj));
} else {
json.append(bean2json(obj));
}
return json.toString();
} public static String bean2json(Object bean) {
StringBuilder json = new StringBuilder();
json.append("{");
PropertyDescriptor[] props = null;
try {
props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
} catch (IntrospectionException e) {}
if (props != null) {
for (int i = 0; i < props.length; i++) {
try {
String name = object2json(props[i].getName());
String value = object2json(props[i].getReadMethod().invoke(bean));
json.append(name);
json.append(":");
json.append(value);
json.append(",");
} catch (Exception e) {}
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
} public static String list2json(List<?> list) {
StringBuilder json = new StringBuilder();
json.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
} public static String array2json(Object[] array) {
StringBuilder json = new StringBuilder();
json.append("[");
if (array != null && array.length > 0) {
for (Object obj : array) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
} public static String map2json(Map<?, ?> map) {
StringBuilder json = new StringBuilder();
json.append("{");
if (map != null && map.size() > 0) {
for (Object key : map.keySet()) {
json.append(object2json(key));
json.append(":");
json.append(object2json(map.get(key)));
json.append(",");
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
} public static String set2json(Set<?> set) {
StringBuilder json = new StringBuilder();
json.append("[");
if (set != null && set.size() > 0) {
for (Object obj : set) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
} public static String string2json(String s) {
if (s == null)
return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch >= '\u0000' && ch <= '\u001F') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}
return sb.toString();
}
}
web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>showInfoServlet</servlet-name>
<servlet-class>client_servlet.showInfoServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>JsonServlet</servlet-name>
<servlet-class>client_servlet.JsonServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ajaxServlet</servlet-name>
<servlet-class>client_servlet.ajaxServlet</servlet-class>
</servlet> <filter>
<filter-name>myFilter</filter-name>
<filter-class>utils.CrossDomainFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <servlet-mapping>
<servlet-name>showInfoServlet</servlet-name>
<url-pattern>/servlet/showInfoServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>JsonServlet</servlet-name>
<url-pattern>/servlet/JsonServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ajaxServlet</servlet-name>
<url-pattern>/servlet/ajaxServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app> 用于处理业务逻辑的servlet:
package client_servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javabean.Route;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import services.RouteService;
import utils.JsonUtil; public class showInfoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin","*");
response.setContentType("text/html; charset=UTF-8");//jsonp其实回写的就是一段JavaScript代码
PrintWriter out = response.getWriter();
//从数据库查询所有的路线route的集合list
RouteService rs = new RouteService();
String res = JsonUtil.list2json(rs.listAll());
out.print(res);
out.flush();
out.close();
}
}

  

通过hbuilder建立的demo.html文件:

该文件用于请求后台的servlet并且接受服务器端返回的json数据

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />

<title>hello world</title>

<script src="js/mui.min.js"></script>

<link href="css/mui.min.css" rel="stylesheet" />

<script type="text/javascript">

if(window.plus) {

plusReady();

} else {

document.addEventListener("plusready", plusReady(), false);

}

function plusReady() {

}

//创建一个新的页面

function createNewWeb() {

var url = "http://www.jiangbobobo.cn/smart";

plus.webview.create(url).show();

}

//发送数据的函数

function postData(url, data, callback) {

mui.ajax(url, {

data: 'data=' + JSON.stringify(data),

dataType: 'json',

type: 'get',

contentType: "application/x-www-form-urlencoded; charset=utf-8",

timeout: 6000000,

success: callback,

error: function(xhr, type, errorThrown) {

//waitingDialog.close();

mui.alert("<网络连接失败,请重新尝试一下>", "错误", "OK", null);

console.log(type);

console.log(JSON.stringify(xhr));

}

});

}

function test() {

var data = {};

postData('http://192.168.17.1:8080/zannadu/servlet/showInfoServlet',

data, // json 数据

function(json) {

//mui.alert("hello");

var html = "";

var x = document.getElementById("mycard");

//mui.alert(str);

for(var i = 0; i < json.length; i++) {

//mui.alert(json[i].imageURL);

html += "<div class='mui-card'>";

html += "<div class='mui-card-header mui-card-media' style='height:40vw;background-image:url(" + json[i].imageURL + ")'></div>";

html += "<div class='mui-card-content'>";

html += "<div class='mui-card-content-inner'>";

html += "<div class='mui-content'>";

html += "<h4>" + json[i].name + "</h4>";

html += "<p id='route_description'>";

html += "" + json[i].service_content + "";

html += "</p>";

html += "</div>";

html += "</div>";

html += "</div>";

html += "<div class='mui-card-footer'>";

html += "<a class='mui-card-link'>" + json[i].like_number + "</a>";

html += "<a class='mui-card-link'>" + json[i].old_price + "</a>";

html += "<a class='mui-card-link'>" + json[i].new_price + "</a>";

html += "</div>";

html += "</div>";

x.innerHTML = html;

}

}

);

}

</script>

</head>

<body onload="test()">

<!--<button onclick="createNewWeb()">show data</button>-->

<!--<input type="button" value="test" onclick="test()" />-->

<div class="mui-content" id="mycard">

</div>

</body>

</html>

ajax跨域访问数据的更多相关文章

  1. 关于试用jquery的jsonp实现ajax跨域请求数据的问题

    我们在开发过程中遇到要获取另一个系统数据时,就造成跨域问题,这就是下文要说的解决办法: 先我们熟悉下json和jsonp的区别: 使用AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交 ...

  2. 浅析JSONP-解决Ajax跨域访问问题

    浅析JSONP-解决Ajax跨域访问问题 很久没有写随笔了,总是感觉没时间,其实时间就是...废话少说,前几天,工作上有一新需求,需要前端web页面异步调用后台的Webservice方法返回信息.实现 ...

  3. Ajax跨域访问

    Ajax如何跨域访问数据 最近在做项目的过程中遇到的问题,一个网站需要访问另外一个网站的数据,并且是通过脚本的方式,而由于同源策略的限制,开发人员不能再与外部服务器进行通信的时候使用XMLHttpRe ...

  4. Ajax跨域访问解决办法

    方法1. jsonp实现ajax跨域访问示例 jsp代码: <body> <input type="button" onclick="testJsonp ...

  5. Web Api 2(Cors)Ajax跨域访问

    支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示   随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细.比如前端项目使用Ang ...

  6. Vue用axios跨域访问数据

    Vue用axios跨域访问数据axios是vue-resource的替代品,vue-resource不再维护.安装axios:npm install axios使用vue-cli开发时,由于项目本身启 ...

  7. Hbuilder编辑App时,ajax跨域访问失败问题

    今天试着用Hbuilder写app的前段显示页面,在第一步时就被打住了,ajax异步调用服务器的登录接口时,报错, 显示这样的错误 XMLHttpRequest cannot loadhttp://w ...

  8. ajax跨域访问http服务--jsonp

    在前面一篇文章<Spring Cloud 前后端分离后引起的跨域访问解决方案>里我们提到使用ajax跨域请求其他应用的http服务,使用的是后台增加注解@CrossOrigin或者增加Co ...

  9. ajax跨域访问的解决方案

    今天的工作中要访问摄像机内部的一个web站点,这就涉及到jquery的ajax跨域访问的问题.我使用的是jquery1.7的版本,下面总结如下: 问题一:一开始用IE调试,总是返回No Transpo ...

随机推荐

  1. Installing the JMeter CA certificate for HTTPS recording

    参考: http://jmeter.apache.org/usermanual/component_reference.html#HTTP(S)_Test_Script_Recorder User m ...

  2. 2019nc#10

    题号 标题 已通过代码 题解/讨论 通过率 团队的状态 A Blackjack 点击查看 背包DP 32/109 补好了 B Coffee Chicken 点击查看 进入讨论 738/2992  通过 ...

  3. cogs 2652. 秘术「天文密葬法」(0/1分数规划 长链剖分 二分答案 dp

    http://cogs.pro:8080/cogs/problem/problem.php?pid=vSXNiVegV 题意:给个树,第i个点有两个权值ai和bi,现在求一条长度为m的路径,使得Σai ...

  4. CH 5101 最长公共上升子序列

    题目传送门 题解:F[i][j] 表示 对于第一个数列枚举到i来说, 第二个数列以j结尾的最大长度是多少. 那么对于更新 F[i] -> F[i+1]来说  如果 a[i+1] == b[j] ...

  5. CF - 652 E Pursuit For Artifacts 边双联通

    题目传送门 题解总结起来其实很简单. 把所有的边双联通分量缩成一个点,然后建立好新边, 然后再从起点搜到终点就好了. 代码: /* code by: zstu wxk time: 2019/02/23 ...

  6. lightoj 1125 - Divisible Group Sums (dp)

    Given a list of N numbers you will be allowed to choose any M of them. So you can choose in NCM ways ...

  7. 牛客小白赛5 无关(relationship) 容斥原理(计算因子数的模板)

    链接:https://www.nowcoder.com/acm/contest/135/A来源:牛客网 若一个集合A内所有的元素都不是正整数N的因数,则称N与集合A无关.   给出一个含有k个元素的集 ...

  8. codeforces 486 D. Valid Sets(树形dp)

    题目链接:http://codeforces.com/contest/486/problem/D 题意:给出n个点,还有n-1条边的信息,问这些点共能构成几棵满足要求的树,构成树的条件是. 1)首先这 ...

  9. Kafka笔记—可靠性、幂等性和事务

    这几天很忙,但是我现在给我的要求是一周至少要出一篇文章,所以先拿这篇笔记来做开胃菜,源码分析估计明后两天应该能写一篇.给自己加油~,即使没什么人看. 可靠性 如何保证消息不丢失 Kafka只对&quo ...

  10. 时间复杂度big-O、Big-Omega和big-Theta

    我们有三种曲线:   A curve that we know is "above" the running time function when n is large. ( Bi ...