Cross-domain problem with GET request URL in parsing Angularjs _angularjs

Source: Internet
Author: User
Tags domain server


This morning to help students see a angularjs problem, mainly in the request for Cross-domain access, the request was blocked.



Here's the code she gave me:


<html lang = "en" 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}}" />
         <p> Name: <span> {{data.goodsName}} </ span> </ p>
         <p> Price: <span> {{data.price | currency: "¥"}} </ span> </ p>
       </ li>
     </ ul>
   </ div>
</ body>
</ html>


Problems that arise



We can see that he is through the $http get way to access the URL, has been unable to access, I will be specific response print to the console, but also caused a problem.






This is the browser across the domain caused by the previous study I was not very clear this, just know that because not under the same domain name to access the resources under the domain will cause cross-domain. In fact, I saw this before because the request format is problematic and the returned JSON data is not available.



The following is the data returned in JSON format.






According to the URL she gave me, I found a callback in front of the JSON data, this is a callback function in PHP, the result of a search on the web found that a GET request is not useful for this callback function.



Solutions



The following method must be used to handle this data in a callback JSONP format.


<script>
  var myApp = angular.module ("App", []);
  Myapp.controller ("Test", Function ($scope, $http) {
    //callback function usage
    myurl = "http://datainfo.duapp.com/shopdata/ Getgoods.php?callback=json_callback ";
    $http. JSONP (Myurl). Success (function (response) {
      Console.log (response);
    }
); </script>


Note two points:


    • Use $HTTP.JSONP () to request data (resolution of cross-domain issues)
    • Add callback=json_callback characters after the URL;


This makes it possible to access the data normally. In fact, for JSON-formatted data, if we want to know where there is a mistake, one way is to print it to the browser's console so that we can see the specific process and results.



Complete 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) {
       // callback function usage
       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">
         <!-AngularJS in scr cannot be written like this->
         <img src = "{{data.goodsListImg}}" />
         <p> Name: <span> {{data.goodsName}} </ span> </ p>
         <p> Price: <span> {{data.price | currency: "¥"}} </ span> </ p>
       </ li>
     </ ul>
   </ div>
</ body>  





Automatically replaces our json_callback with the following characters, which should be angularjs replaced.






Reference



How cross domains are resolved:



By using JSON to pass data and jsonp across domains, JSON is a data interchange format, and Jsonp is an unofficial Cross-domain data interaction protocol created by developers ' ingenuity;



How the JSONP is produced:


    • A well-known problem, Ajax direct request Common files have Cross-domain access to the problem, no matter what you are static pages, dynamic Web pages, Web services, WCF, as long as the Cross-domain request, are not allowed;
    • However, we also found that the Web page on the call JS file is not affected by the cross-domain (not only that, we also found that all have "src" this attribute of the label has cross-domain capabilities, such as <script>, , <iframe> );
    • It can be judged that the current phase if you want to access data across domains through a purely web-side (ActiveX control, Server Proxy, WebSocket of the future HTML5, etc.) is only one possibility, that is, trying to load data into a JS file in a remote server, For client invocation and further processing;
    • It happens that we already know that there is a plain character data format called JSON that succinctly describes complex data, and, even better, that JSON is supported by JS native, so that the data in this format can be handled almost arbitrarily at the client's disposal.
    • This solution is now apparent, the Web client through the same way as the call script to invoke the dynamically generated JS format file on the Cross-domain server (generally with JSON suffix), it is obvious that the server is to dynamically generate JSON files, the purpose is to load the data required by the client into.
    • After the client has successfully invoked the JSON file, it gets the data that it needs, and the rest is processed and displayed on its own terms, and the way to get the remote data looks very much like Ajax, but it's not the same.
    • In order to facilitate the use of data by the client, an informal transport protocol has been developed, which is called Jsonp, and one of the key points of this protocol is to allow the user to pass a callback parameter to the server, The server side then returns the data by wrapping the callback parameter as the 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 the request;
    • Specifies the name of the callback and callback function, when the function name is Json_callback, callback the success function, json_callback must all uppercase;
    • You can also specify other callback functions, but you must define global functions under Windows.
    • Callback must be added to the URL;


Browsers have homologous policies that prohibit a page from loading or executing any script that is different from its own source at the global level; JSONP is a way to circumvent the browser's security restrictions and request data from different domains;






This explanation is sufficient to understand cross-domain problems and why you need to use JSONP?



The above is the entire content of this article, I hope to help you, but also hope that a lot of support cloud Habitat community!


Related Article

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.