Làm cách nào để thực hiện yêu cầu HTTP trong Javascript và PHP?
Dec 15 2022
Để thực hiện một yêu cầu HTTP trong JavaScript, bạn có thể sử dụng đối tượng XMLHttpRequest hoặc API tìm nạp mới hơn. Đây là một ví dụ sử dụng XMLHttpRequest: Lưu ý rằng API tìm nạp chỉ được hỗ trợ trong các trình duyệt hiện đại, vì vậy bạn có thể cần sử dụng một polyfill hoặc quay lại sử dụng XMLHttpRequest cho các trình duyệt cũ hơn.
Để thực hiện một yêu cầu HTTP trong JavaScript, bạn có thể sử dụng XMLHttpRequestđối tượng hoặc fetchAPI mới hơn.
Đây là một ví dụ sử dụng XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.example.com/', true);
xhr.onload = function() {
if (this.status == 200) {
var data = JSON.parse(this.response);
console.log(data);
}
};
xhr.send();
fetch('https://www.example.com/')
.then(response => response.json())
.then(data => console.log(data));
Lưu ý rằng fetchAPI chỉ được hỗ trợ trong các trình duyệt hiện đại, vì vậy bạn có thể cần sử dụng polyfill hoặc quay lại sử dụng XMLHttpRequestcho các trình duyệt cũ hơn.
Và để thực hiện một yêu cầu HTTP trong PHP, bạn có thể sử dụng hàm tích hợp sẵn file_get_contents() hoặc thư viện cURL mạnh mẽ hơn.
Sử dụng file_get_contents():
<?php
// Set the URL of the request
$url = 'http://www.example.com';
// Send the request and store the response
$response = file_get_contents($url);
// Check for errors
if($response === false) {
// Handle error
} else {
// Use the response
}
?>
<?php
// Initialize cURL
$ch = curl_init();
// Set the URL of the request
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
// Send the request and store the response
$response = curl_exec($ch);
// Check for errors
if(curl_errno($ch)) {
// Handle error
} else {
// Use the response
}
// Close the cURL handle
curl_close($ch);
?>
![Dù sao thì một danh sách được liên kết là gì? [Phần 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































