search
HomeBackend DevelopmentPHP TutorialSeveral ways of cross-domain php

Several ways of cross-domain php

Sep 21, 2019 pm 05:55 PM
phpCross domain

Several ways of cross-domain php

Several forms of cross-domain implementation in PHP

##1. JSONP (JSON with padding) principle

Use the script tag in HTML to load js in other domains, and use script src to obtain data in other domains. However, because it is introduced through tags, So, the requested JSON format data will be run and processed as js. Obviously, this operation will not work.

Therefore, it is necessary to package the returned data in advance and encapsulate it into a function for running processing. The function name is passed to the background through the interface parameter transfer method. After the background parses the function name, it will be used in the original Wrap this function name on the data and send it to the front end. (JSONP requires the cooperation of the backend of the corresponding interface to achieve)

Example:

<script>function showData(ret){
console.log(ret);
}</script><script src="http://api.jirengu.com/weather.php?callback=showData"></script>

When the script src request reaches the backend, the backend It will parse the callback parameter, obtain the string showData, return the data after sending the data, and encapsulate it with showData, that is, showData({"json data"}). After the front-end script tag loads the data, it will use the json data as Parameters of showData, call the function to run.

2. CORS

The full name of CORS is cross-origin resource sharing (

Cross-Origin Resource Sharing), which is a An ajax cross-domain resource request method that supports modern browsers, and IE supports 10 and above.

Implementation method:

When using

XMLHttpRequest to send a request, the browser finds that the request does not comply with the same-origin policy and adds the A request header: Origin, and a series of processing is performed in the background. If the request is determined to be accepted, a response header is added to the return result: Access-Control-Allow-Origin; the browser determines Does the corresponding header contain the value of Origin? If so, the browser will process the response and we can get the response data. If not, the browser will directly reject it. At this time, we cannot get the response data.

Example:

server.js

var http = require(&#39;http&#39;)
var fs = require(&#39;fs&#39;)
var path = require(&#39;path&#39;)
var url = require(&#39;url&#39;)http.createServer(function(req, res){
var pathObj = url.parse(req.url, true)

  switch (pathObj.pathname) {
    case &#39;/getNews&#39;:
      var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心"
        ]

      res.setHeader(&#39;Access-Control-Allow-Origin&#39;,&#39;http://localhost:8080&#39;)
      //res.setHeader(&#39;Access-Control-Allow-Origin&#39;,&#39;*&#39;)
      res.end(JSON.stringify(news))
      break;
    default:
      fs.readFile(path.join(__dirname, pathObj.pathname), function(e, data){
        if(e){
          res.writeHead(404, &#39;not found&#39;)
          res.end(&#39;<h1 id="nbsp-Not-nbsp-Found">404 Not Found</h1>&#39;)
        }else{
          res.end(data)
        }
      }) 
  }}).listen(8080)

index.html

<!DOCTYPE html><html><body>
  <div class="container">
    <ul class="news"></ul>
    <button class="show">show news</button>
  </div><script>
  $(&#39;.show&#39;).addEventListener(&#39;click&#39;, function(){
    var xhr = new XMLHttpRequest()
    xhr.open(&#39;GET&#39;, &#39;http://127.0.0.1:8080/getNews&#39;, true)
    xhr.send()
    xhr.onload = function(){
      appendHtml(JSON.parse(xhr.responseText))
    }
  })
  function appendHtml(news){
    var html = &#39;&#39;
    for( var i=0; i<news.length; i++){
      html += &#39;<li>&#39; + news[i] + &#39;</li>&#39;
    }
    $(&#39;.news&#39;).innerHTML = html
  }
  function $(selector){
    return document.querySelector(selector)
  }
  </script>
  </html>

3 , postMessage

Assuming there are two domain names (the domain names of the main domain are inconsistent), and the iframe page is allowed to access the call, then it can be implemented with postMessage.

Principle: a domain name sends a request for postMessage, and b domain name hears the message event, and processes and returns the data

//b域名<script>window.frames[0].postMessage(this.value, &#39;*&#39;);
//*号表示在任何域下都可以接收message
window.addEventListener(&#39;message&#39;, function(e){
  console.log(e.data);
});</script>

The above content is only for refer to!

Recommended tutorial:

PHP video tutorial

The above is the detailed content of Several ways of cross-domain php. For more information, please follow other related articles on the PHP Chinese website!

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor