Breakthrough in cross-origin access restrictions of ajax
Ajax cross-origin access encounters this exception:
XMLHttpRequest cannot load http: // 10.43.15.23/hnsh/rest/waterInfo/getRiverInfo. do. no 'access-Control-Allow-origin' header is present on the requested resource. origin 'HTTP: // localhost: 100' is therefore not allowed access.
Generally, the server (tomcat java) is used to redirect requests:
Public static String getJson (String url) {String path = url; List list = new ArrayList (); String content = ""; // read the url content Set set = new HashSet (); try {URL cumtURL = new URL (path); URLConnection cumtConnection = cumtURL. openConnection (); DataInputStream din = new DataInputStream (cumtConnection. getInputStream (); String inputLine = ""; while (inputLine = din. readLine ())! = Null) {content + = inputLine;} content = new String (content. getBytes ("ISO-8859-1"), "UTF-8 "). trim (); din. close ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace (); return null;} return content ;}In the page (jquery ):
$ ("# B2 "). click (function () {$. getJSON ("http: // ip: 8080/hnsh/rest/getInfo. do ", function (data, status) {alert (" data: "+ data. list. length + "\ n status:" + status );});});
If you use
JsonpFor direct cross-origin, add yoururl? Callback = ?, Native support of jquery,
In the page (jquery ):
$ ("# B2"). click (function () {$. getJSON ("http: // 10.43.15.23/hnsh/rest/waterInfo/getRiverInfo. do? Callback =?", Function (data, status) {alert (" data: "+ data. list. length +" \ n status: "+ status );});});
In this case, you still need to modify the server to support callback; see (see: http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1)
Otherwise, even if the request arrives at a foreign data source, the parsing error will occur:
Uncaught SyntaxError: Unexpected token:
There is also a way to disable cross-origin security restrictions on the browser, that is, the "disable web security" page and the server do not move any code:
Taking firefox as an example, you can install an extension component:
Extension address: http://spenibus.net/files/gitbin/cors-everywhere-firefox-addon/
Restart the browser to enable the extension in customization:
Find this component, drag it to the end of the search bar, and click Enable. Now, it's okay with cross-origin restrictions: