Home  >  Article  >  Web Front-end  >  Parsing cross-domain issues in get request URLs in AngularJS

Parsing cross-domain issues in get request URLs in AngularJS

高洛峰
高洛峰Original
2016-12-03 10:17:271271browse

This morning I helped a classmate look at an AngularJS problem. The main problem was that cross-domain access occurred in the request and the request was blocked.

The following is the code she gave me:

<html ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <!--<script src="../js/jquery-1.11.0.js"></script>-->
  <script src="angular.min.js"></script>
  <script>
    angular.module("myApp",[]).controller("test",["$scope","$http",function($scope,$http){
        $http.get("http://datainfo.duapp.com/shopdata/getGoods.php?classID=1")
        .success(function(response){
          $scope.myarr = response.sites;
        })
    }])
  </script>
</head>
<body>
  <div ng-controller="test">
    <ul>
      <li ng-repeat="data in myarr">
        <img  src="{{data.goodsListImg}}"/ alt="Parsing cross-domain issues in get request URLs in AngularJS" >
        <p>名称:<span>{{data.goodsName}}</span></p>
        <p>价格:<span>{{data.price|currency:"¥"}}</span></p>
      </li>
    </ul>
  </div>
</body>
</html>

The problem

We can see that he accesses the URL through the get method of $http, but it cannot be accessed. I printed the specific response to the console and also used something is wrong.

Parsing cross-domain issues in get request URLs in AngularJS

This is caused by cross-domain browsers. I was not very clear about this in my previous studies. I just know that cross-domain will occur because resources under this domain name are not accessed under the same domain name. In fact, when I saw this before, I thought there was something wrong with the format of the request, and the returned json data could not be received.

The following is the data returned in json format.

Parsing cross-domain issues in get request URLs in AngularJS

According to the URL she gave me, I found that there is a callback in front of the json data. This is the callback function in php. As a result, I searched online and found that the get request has no effect on this callback function.

Solution

You must use the following method to process this kind of jsonp format data with callback.

<script>
  var myApp = angular.module("App", []);
  myApp.controller("test", function($scope, $http) {
    // 回调函数用法
    myUrl = "http://datainfo.duapp.com/shopdata/getGoods.php?callback=JSON_CALLBACK";
    $http.jsonp(myUrl).success(function(response) {
      console.log(response);
    });
  });
</script>

Pay attention to two points:

Use $http.jsonp() to request data; (solve the cross-domain problem)

Add the callback=JSON_CALLBACK character after the URL;

This way you can access the data normally. In fact, if we want to know where there are errors in data in json format, one way is to print it to the browser console, so that we can see the specific process and results.

Full code

<!DOCTYPE html>
<html ng-app="App">
 
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="angular.min.js"></script>
  <script>
    var myApp = angular.module("App", []);
    myApp.controller("test", function($scope, $http) {
      // 回调函数用法
      myUrl = "http://datainfo.duapp.com/shopdata/getGoods.php?callback=JSON_CALLBACK";
      $http.jsonp(myUrl).success(function(response) {
        console.log(response);
        $scope.myarr = response;
      });
    });
  </script>
</head>
 
<body>
  <div ng-controller="test">
    <ul>
      <li ng-repeat="data in myarr">
        <!--scr里面的angularJS不可以这样写-->
        <img  src="{{data.goodsListImg}}" / alt="Parsing cross-domain issues in get request URLs in AngularJS" >
        <p>名称:<span>{{data.goodsName}}</span></p>
        <p>价格:<span>{{data.price|currency:"¥"}}</span></p>
      </li>
    </ul>
  </div>
</body>

Parsing cross-domain issues in get request URLs in AngularJS

automatically replaces our JSON_CALLBACK with the following characters, which should be replaced by AngularJS.

Parsing cross-domain issues in get request URLs in AngularJS

Quote

How cross-domain is solved:

Transfer data through json, rely on jsonp to cross-domain, json is a data exchange format, and jsonp is a format created by the ingenuity of developers An unofficial cross-domain data interaction protocol;

How JSONP was generated:

A well-known problem, Ajax direct request for ordinary files has the problem of cross-domain unauthorized access, regardless of whether you are a static page, a dynamic web page, or a web page Services, WCF, as long as it is a cross-domain request, are not allowed;

However, we also found that when calling js files on the Web page, it is not affected by whether it is cross-domain (not only that, we also found that any request that has the "src" attribute All tags have cross-domain capabilities, such as <script>, <img alt="Parsing cross-domain issues in get request URLs in AngularJS" >, <iframe>); </script>

So it can be judged that if you want to use pure web side (ActiveX control, server-side proxy, etc.) at the current stage, it belongs to the future There is only one possibility for cross-domain access to data (excluding HTML5's Websocket and other methods), and that is to try to load the data into a js format file on the remote server for client calling and further processing;

Coincidentally, we already know There is a pure character data format called JSON that can describe complex data concisely. What’s even better is that JSON is also natively supported by js, so the client can process data in this format almost as desired;

So a solution is ready to come out Now, the web client calls the js format file dynamically generated on the cross-domain server (usually with JSON as the suffix) in exactly the same way as calling the script. It is obvious that the reason why the server dynamically generates the JSON file is to convert the client Load the required data.

After the client successfully calls the JSON file, it also obtains the data it needs. The rest is to process and display it according to its own needs. This method of obtaining remote data looks very much like AJAX, but in fact Not the same.

In order to facilitate the client to use data, an informal transmission protocol has gradually formed. People call it JSONP. One of the key points of this protocol is to allow users to pass a callback parameter to the server, and then the server will return the data when it returns. This callback parameter is used as a function name to wrap the JSON data, so that the client can customize its own function to automatically process the returned data.

Processing jsonp data in AngularJS

Use the $http.jsonp() function to send requests;

Specify the callback and callback function name. When the function name is JSON_CALLBACK, the success function will be called back. JSON_CALLBACK must be all capital letters;

Also available Specify other callback functions, but they must be defined as global functions under the window;

callback must be added to the URL;

The browser has a same-origin policy, which prohibits page loading or execution from domains different from its own source at the global level Any script; JSONP is a way to request data from different domains, bypassing browser security restrictions;

Parsing cross-domain issues in get request URLs in AngularJS

This explanation is enough to understand cross-domain issues and why you need to use JSONP?

Statement:
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