Frontend Development 4 min read

Cross-Domain Communication in Web Development Using PHP (JSONP Example)

This article explains cross‑domain communication in web development, outlines common methods such as JSONP, CORS, iframe + postMessage and proxy, and provides a PHP example of JSONP implementation with client‑side script to demonstrate data transfer across different domains.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Cross-Domain Communication in Web Development Using PHP (JSONP Example)

Cross‑domain communication refers to the process of transferring data between web pages that are hosted on different domains, which is normally blocked by the browser's same‑origin policy.

Common techniques to achieve cross‑domain communication include:

JSONP – inserting a <script> tag that loads a remote script which calls a predefined callback function.

CORS – configuring the server to send specific response headers that allow browsers to make cross‑origin requests.

iframe + window.postMessage() – embedding an <iframe> from another domain and using the HTML5 messaging API for secure communication.

Proxy – having the same‑origin server request data from the target domain and then relay it to the client.

The article provides a PHP implementation of JSONP. The server reads the callback name from $_GET['callback'] , prepares an array of data, encodes it with json_encode() , and echoes the callback with the JSON payload:

<?php
// Get the callback function name
$callback = $_GET['callback'];

// Data to return
$data = ['name' => 'John', 'age' => 25];

// Output JSONP
echo $callback . '(' . json_encode($data) . ')';
?>

On the client side, a <script> element is created dynamically, its src attribute points to the PHP endpoint with the callback parameter, and the script is appended to the document head. When the server responds, the callback function receives the data:

<script>
function handleData(data) {
    console.log(data);
}

var script = document.createElement('script');
script.src = 'http://example.com/api.php?callback=handleData';
document.getElementsByTagName('head')[0].appendChild(script);
</script>

By selecting the appropriate method based on project requirements, developers can enable reliable data exchange across different domains in web applications.

frontendPHPJSONP
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.