Home > Web Front-end > JS Tutorial > body text

3 common methods for js cross-domain request data_javascript skills

WBOY
Release: 2016-05-16 15:28:32
Original
1539 people have browsed it

Due to the influence of the js origin policy, when requesting other domain names under a certain domain name, or URLs under the same domain name and different ports, it will become a cross-domain request that is not allowed.
So how do you usually solve the problem at this time? I have sorted it out a little:
1.JavaScript
In the case of native js (without jQuery and ajax support), usually the client code is like this (I assume it is http://localhost:8080/webs/i.mediapower.mobi/wutao under the port of localhost:8080 Add the following code below the body tag of the /index.html page):

<script>
  var xhr = new XMLHttpRequest();
  xhr.open("get", "http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js", true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      console.log(xhr.responseText);
    }
  };
  xhr.send(null);
</script>
Copy after login

Save, open http://localhost:8080/webs/i.mediapower.mobi/wutao/index.html in the browser, and open the console console:


The browser will ruthlessly pop up a same-origin restriction error for you, which means that you cannot request the data of the URL across domains.
So, I will first adopt the first strategy, using the script tag in HTML to insert the js script:
(1) Reference through the script tag and write down the url address of the src you need, For example:

<script>
var callbackfunction = function(data) {
  console.log('我是跨域请求来的数据-->' + data.name);
};
</script>
<script src="http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js&#63;callback=callbackfunction"></script> 
Copy after login

Here I define a callback function, and then use the src attribute of the script tag to request data across domains. Then, the content of test.js has been agreed and needs to be written like this:
callbackfunction({"name":"wwwwwwwwwwww"});
Save, open index.html and refresh:


(2) You can also dynamically add script tags to dynamically load scripts and request remote data when HTML is parsed:

<script>
var callbackfunction = function(data) {
  console.log('我是跨域请求来的数据-->' + data.name);
};
var script = document.createElement('script'),
  body = document.getElementsByTagName('body');

script.src = 'http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js&#63;callback=callbackfunction';
body[0].appendChild(script);
</script>

Copy after login

The result is the same as above.

2.$.ajax() in jQuery

Imagine that when you want to use jQuery to request cross-domain data, for example (still the index.html just now):

<script src="js/jquery-1.11.3.js"></script>
<script>
$(function(){
  $.get('http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js',function(data){
    console.log(data);
  })
})
</script>
Copy after login

The browser still reports an error mercilessly because your URL is under a different domain name.

So since jQuery encapsulates the ajax method, why don’t we use it? They have encapsulated it. If you don’t use it, wouldn’t you be asking for trouble? The code is as follows:

<script src="js/jquery-1.11.3.js"></script>
<script>
$(function(){
  $.ajax({
    async: false,
    type: "GET",
    dataType: 'jsonp',
    jsonp: 'callback',
    jsonpCallback: 'callbackfunction',
    url: "http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js",
    data: "",
    timeout: 3000,
    contentType: "application/json;utf-8",
    success: function(msg) {
      console.log(msg);
    }
  });
})
</script>
Copy after login

After you did so much teasing work, the browser responded readily, saying that it was very happy, and returned an object to you, which contained the data in test.js under different remote domain names.
3.postMessage iframe

PostMessage is a newly added function in HTML5. For example, in my local domain name, testa.html in http://192.168.1.152:8080/webs/i.mediapower.mobi/wutao/testa.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>testa</title>
</head>
<script>
window.onload = function() {
  document.getElementById('ifr').contentWindow.postMessage('我是要经过传递的数据', 'http://i2.mediapower.mobi/adpower/vm/Bora/testb.html');
};
</script>
<body>
  <iframe id="ifr" src="http://i2.mediapower.mobi/adpower/vm/Bora/testb.html"></iframe>
</body>
</html>
Copy after login

At this point, the content in my remote testb.html should be like this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>testb</title>
</head>
<script>
window.addEventListener('message', function(event) {
  // 通过origin属性判断消息来源地址
  if (event.origin === 'http://192.168.1.152:8080') {
    alert(event.data); 
  }
}, false);
</script>
<body>
123
</body>
</html>

Copy after login

Save the code, open the local testa.html, and access the remote testb.html


To summarize, jQuery is still very easy to use. Basically, jQuery can complete everything that js can do very quickly and efficiently. Of course, native js can also solve many things, and the new features of HTML5 are also very powerful. , among these methods, I still recommend jQuery.

The above are 3 commonly used js cross-domain request data methods shared with you. I hope it will be helpful to your learning.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template