Deep Understanding of JSONP Cross-Domain Access API Interface

Time:2019-9-11

Explain

There are as many as seven or eight solutions to cross-domain problems. Don’t say that there are so many. I’m not serious with you, nor are you serious with me?! VoluntarilyBaiduorGoogleI won’t tell you so many things here, just the most used one.JSONPYou have to sayJSONPIt’s not the most used. I don’t believe it. You believe it. Ha-ha, are you happy?

About cross domain

  • Browser Homology Policy

To understand what isCross domainYou need to know what browser homology strategy is

  • Resource Requirements for Browsers to Allow Access

As a matter of fact, just one sentence.Same domain name, same protocol, same portBrowsers only allow access, this is due to security considerations, all other access is not allowed!

  • Common View of Homologous Resources Allowed by Browsers

For instance:a.com/article/mid/512To visita.com/data/detail/512Access is allowed.a.com/article/mid/512To visitb.com/data/detail/512No!

  • Accessing B Domain Name Resources under A Domain Name

So what if you have to access resources under different domain names? So here comes the question…! Cross domain

Do not use cross-domain access

This is the normal way to access other domain name resource URLs without cross-domain access! Accessing other domain name resource URLs is not feasible!

Front-end code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSONP TEST</title>
    <script></script>
</head>
<body>

<script>
    $.ajax({
        type : 'GET',
        dataType : 'JSON',
        url : "http://warnerwu.centos.dev/?c=adCreativeLib&a=api&type=list",
        success : function (data){
            console.log(data);
        }
    });
</script>
</body>
</html>

Browser Developer Tools Console Tips

It can be found that the console does not output any return data, because it does not have any data to output, but gives the following prompt information:

Deep Understanding of JSONP Cross-Domain Access API Interface

Details of Web Request List for Browser Developer Tools

In the network request list, you can see that the request resource URL does not return any data.

Deep Understanding of JSONP Cross-Domain Access API Interface

Backend return data form

Since passedjQueryOfAJAXMethod returns data in the form ofJSONFormat, request resource URLs, no data is obtained, direct access to resource URLs through browsers can normally obtain data!

Deep Understanding of JSONP Cross-Domain Access API Interface

Using JSONP to access resources across domains

Front-end or client processing

From the above, you can see that direct access to resource URLs through browsers, that is, API interfaces, can obtain data, and return data in the form ofJSONThe way to deny access is to passtem.mac.devAccess to this domain namewarnerwu.centos.devAPI interface URL resources under domain names need to be usedJSONPAll you need to do is tojQueryinAJAXMethod indataTypeChange the value to

dataType : 'JSONP'

Be careful

This is only limited to the above mentioned “access the data directly through the browser API interface URL” through the form of JSONP to obtain, but only so, the next refresh page throughJSONPAccess the resource API interface URL to verify this!

Browser Developer Tools Console Tips

No longer visible under the consoleIntercepted cross-domain requestsWarning message! ButAbsolutely emptyOh

Deep Understanding of JSONP Cross-Domain Access API Interface

Details of Web Request List for Browser Developer Tools

Now that I am inConsoleI can’t see anything.warningYou can’t see the data output either. Just take a look.networkWhat about the request list?

Deep Understanding of JSONP Cross-Domain Access API Interface

fromnetworkThe last item in the request list shows that the complete URL of the API interface for accessing resources is:

http://warnerwu.centos.dev/?c=adCreativeLib&a=api&type=list&callback=jQuery21408945840059161158_1519958486174&_=1519958486175

Here you will find the resource address of the request withAJAXMethod inurlThe parameter values are quite different! It has two more parameters:

callback=jQuery21408945840059161158_1519958486174&_=1519958486175

Well, in usejQueryOfAJAXMethod, if the specified way of returning data isJSONPWhen, that isAJAXLiteral quantity of parameter objectdataType : 'JSONP'As follows:

$.ajax({
    type : 'GET',
    dataType : 'JSONP',
    url : "http://warnerwu.centos.dev/?c=adCreativeLib&a=api&type=list",
    success : function (data){
        console.log(data);
    }
});

It will be at the time of requesting resources.AJAXMethod parameter object literal quantityurlAutomatically add parameters to specific linkscallbackand_And the values of these two parameters are basically never repeated


AJAX parameter object literal quantityurlJSONP parameter value
  • Callback: Value is random tojQueryName of callback function followed by random number string
  • _ Value is a random number string, which guarantees each initiationAJAXRequests are new and do not use the URL requested by the browserCache mechanismExisting resources

Deep Understanding of JSONP Cross-Domain Access API Interface

As you can see in the figure abovenetworkThe API interface accesses the list of specific parameters of the URL in the request resource list, while the API interface accesses the list of specific parameters in the request resource list.responseSpecifically:

Deep Understanding of JSONP Cross-Domain Access API Interface

Can seeresponseReturns data in JSON format, which is wrong! Just look again.Console

Deep Understanding of JSONP Cross-Domain Access API Interface

You can see that the console is still thereAbsolutely empty! Nothing, to the catalogue.Front end or clientThe work done has been completed! Next up isServer sideAPI interface to do some modifications!

Server-side processing

The server-side language used here isPHPThe same is true for other languages.

Actually, the adjustment on the server side is very simple. It only needs to get the request parameters.callbackAnd then go back tocallbackEncoded data string in JSONP format with parameter value as function name

Before API Interface Adjustment

This method is usually used when there is no cross-domain API interface to request data, but it is not common if it is JSONP cross-domain request API interface to obtain data.

Deep Understanding of JSONP Cross-Domain Access API Interface

After API interface adjustment

Deep Understanding of JSONP Cross-Domain Access API Interface

You can see that the data return form is handled here on the server side for general requests, regardless of whether the API interface for cross-domain requests is available or not! __________

Refresh page cross-domain request API interface data again

Deep Understanding of JSONP Cross-Domain Access API Interface

You will find that the request for API interface data is successful, and when requestedcallbackThe parameter values are the same as the returned JSONP format data method names. How to process the JSONP format data?

When the request succeeds, it is executed tojQuerylowerAJAXMethod generatedcallbackThe function of parameter value pair is just the JSONP format data returned from the server. After the function is executed, it returns the subject data, which is the same data form as the data type before the server code returns.

Deep Understanding of JSONP Cross-Domain Access API Interface

Above is the array data output by the cross-domain request API interface through the console

Deep Understanding of JSONP Cross-Domain Access API Interface

Above is the array data obtained by browser directly accessing API interface.

summary

Use it plainlyJQueryOfAJAXIt is very simple to implement cross-domain request resources.

Front-end code

$.ajax({
    type : 'GET',
    dataType : 'JSONP',
    url : "http://warnerwu.centos.dev/?c=adCreativeLib&a=api&type=list",
    success : function (data){
        console.log(data);
    }
});

Server-side code

Deep Understanding of JSONP Cross-Domain Access API Interface

In fact, the very simple question here said so much, you forgive me! ?

The above isDeep Understanding of JSONP Cross-Domain Access API InterfaceThank you for your support!

I hope this article will be helpful to your work and study.

How can I thank you if you think it’s good and you have gained knowledge? Damn it! Praise it!

Good Luck! from warnerwu at 2018.03.02 PM, email address is [email protected]

Recommended Today

Hadoop MapReduce Spark Configuration Item

Scope of application The configuration items covered in this article are mainly for Hadoop 2.x and Spark 2.x. MapReduce Official documents https://hadoop.apache.org/doc…Lower left corner: mapred-default.xml Examples of configuration items name value description mapreduce.job.reduce.slowstart.completedmaps 0.05 Resource requests for Reduce Task will not be made until the percentage of Map Task completed reaches that value. mapreduce.output.fileoutputformat.compress false […]