php+ajax+jsonp 详细使用方法
- PHP with AJAX
AJAX (Asynchronous JavaScript and XML) is a technique used for creating fast and dynamic web pages. It allows you to update a part of your webpage without reloading the whole page. PHP is a server-side scripting language that is used for creating dynamic web pages. Here is an example of how to use PHP with AJAX:
Step 1: Create an HTML file with a form
<!DOCTYPE html>
<html>
<head>
<title>PHP AJAX Example</title>
</head>
<body>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Step 2: Create a PHP file to process the form data
<?php
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
// Do something with the data, like insert into database
echo "Thank you for submitting your information!";
}
?>
Step 3: Create a JavaScript file to handle the AJAX request
$(document).ready(function(){
$('#myForm').submit(function(event){
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: {name: name, email: email},
success: function(response){
$('#result').html(response);
}
});
});
});
- PHP with JSONP
JSONP (JSON with Padding) is a technique used for retrieving data from a different domain using JavaScript. It is useful when you want to retrieve data from a server that does not support CORS (Cross-Origin Resource Sharing). Here is an example of how to use PHP with JSONP:
Step 1: Create a PHP file to return JSON data
<?php
header('Content-Type: application/json');
$data = array(
'name' => 'John Doe',
'email' => 'johndoe@example.com'
);
echo $_GET['callback'] . '(' . json_encode($data) . ')';
?>
Step 2: Create an HTML file to display the data
<!DOCTYPE html>
<html>
<head>
<title>PHP JSONP Example</title>
</head>
<body>
<h1 id="name"></h1>
<p id="email"></p>
<script>
function displayData(data){
document.getElementById('name').innerHTML = data.name;
document.getElementById('email').innerHTML = data.email;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Step 3: Create a JavaScript file to make the JSONP request
$(document).ready(function(){
$.ajax({
url: 'data.php',
dataType: 'jsonp',
jsonpCallback: 'displayData'
});
});
``
原文地址: http://www.cveoy.top/t/topic/gDDy 著作权归作者所有。请勿转载和采集!