Home >Web Front-end >JS Tutorial >How Can I Make Cross-Domain POST Requests in JavaScript Without Page Refresh or Response Parsing?
Problem:
How to perform a cross-domain POST request using JavaScript without refreshing the page or requiring a response parse?
Solution:
Understanding Cross-Origin Resource Sharing (CORS)
To facilitate cross-domain communication, CORS is a standard implemented on the server. By setting response headers on the server, you can grant permission to specific domains to access resources on your own domain.
Server-Side Configuration (Using PHP):
<?php switch ($_SERVER['HTTP_ORIGIN']) { case 'http://from.com': case 'https://from.com': header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Max-Age: 1000'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); break; } ?>
This allows the script from from.com to make cross-domain POST, GET, and OPTIONS requests.
Client-Side AJAX Request (Using jQuery):
$.ajax({ type: 'POST', url: 'https://to.com/postHere.php', crossDomain: true, data: '{"some":"json"}', dataType: 'json', success: function(responseData, textStatus, jqXHR) { var value = responseData.someKey; }, error: function (responseData, textStatus, errorThrown) { alert('POST failed.'); } });
Process:
Considerations:
The above is the detailed content of How Can I Make Cross-Domain POST Requests in JavaScript Without Page Refresh or Response Parsing?. For more information, please follow other related articles on the PHP Chinese website!