Ajax Access data across domains

Source: Internet
Author: User
Tags log log

send and receive data through json, data in JSON format on the server side and the foreground, what is json data? Here is not detailed elaboration, the light oneself Baidu Solves.

When using Ajax Asynchronous requests in html5, you encounter cross-domain problems, If the domain name is inconsistentand theIP address is inconsistent, Port inconsistencies can cause Cross-domain requests to be Unsuccessful.

In order to solve this problem, you need to set the related properties in both foreground and background to make Cross-domain Requests.

Now show the Server-side code:

Self-encapsulated filters:

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, Serv Letresponse resp,filterchain Chain) throws ioexception, servletexception {//TODO auto-generated method Stubhttpservletresponse res = (httpservletresponse) resp;//it is best not to write wildcards here, if you allow multiple domains to request data, you can separate them directly with Commas: "/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}} Convert a string to a JSON data format tool Class: 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 Boo Lean | | 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 &lt ; 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.appe                   nd (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 (obj                   Ect2json (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 configuration file: <?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 EE component</description><display-name> This is the display name of my EE component</display-name><servlet-name>showinfoservlet</servlet-name ><servlet-class>client_seRvlet.showinfoservlet</servlet-class></servlet><servlet><description>this is the Description of my component</description><display-name>this is the display name of my EE component</ Display-name><servlet-name>jsonservlet</servlet-name><servlet-class>client_servlet. Jsonservlet</servlet-class></servlet> <servlet> <description>this is the description of my j2e    E component</description> <display-name>this is the display name of my EE 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& Gt;/servlet/ajaxservlet</url-pattern> </servlet-mapping><welcome-file-list><welcome-file >index.jsp</welcome-file></welcome-file-list></web-app> servlet:package Client_ for handling business logic 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;importOrg.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 actually writes back a piece of JavaScript code printwriter out = Response.getwriter ();  Query the collection of all route routes from the database list Routeservice rs = new Routeservice ();  String res = Jsonutil.list2json (rs.listall ());  Out.print (res);  Out.flush (); Out.close ();}}

  

demo.html files created through hbuilder :

This file is used to request a background servlet and accept JSON data returned by the server side

<! DOCTYPE html>

<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 () {

}

Create a new page

function Createnewweb () {

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

Plus.webview.create (url). Show ();

}

functions for sending data

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 ("< Network connection failed, Please try again >", " error ", "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 + = "

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>

<body onload= "test ()" >

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

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

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

</div>

</body>

Ajax Access data across domains

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.