Simple jQuery, PHP and JSONP example?
jQuery:
$.ajax({
url: "your_php_file.php",
dataType: "jsonp",
success: function(response) {
console.log(response);
}
});
PHP:
<?php
header('Content-Type: application/json');
echo json_encode(["key" => "value"]);
?>
This example uses jQuery's $.ajax()
function to make a JSONP request to a PHP file, which returns a JSON encoded response. The success
function is called when the request is successful and the response is passed as an argument.
Note that, JSONP is a technique that allows you to make cross-domain requests by adding a <script> tag to the HTML document, rather than using the XMLHttpRequest object. JSONP works by creating a script tag whose source is set to the target URL, which is a PHP file in this case, and the PHP file returns a JavaScript object wrapped in a callback function.