我是在 WordPress 主题网站上进行 api 调用的新手。在将我的 api 调用实施到 WordPress 站点之前,我在本地计算机上对其进行了测试。
我在前端使用了 javascript。然后我用php作为后端。这就是我所做的:
这是我的JavaScript代码:
const baseURL ='http://localhost/pledge-test-php/backend/functions.php';
function getOrgs(){
return fetch(`${baseURL}?route=route1`)
.then(response => response.json())
.then(data =>{
console.log(data)
//return renderResults(data.results);
})
.catch(error => console.error('Error:', error));
}
getOrgs();
这是我的functions.php代码:
<?php
// Your PHP code here
//echo json_encode(["message" => "Hello from PHP!"]);
$url = 'https://api.pledge.to/v1/organizations';
$api_key = {my api key goes here};
// Set headers
$context = stream_context_create([
'http' => [
'header' => "Authorization: Bearer $api_key\r\n"
]
]);
if(isset($_GET['route'])) {
$route = $_GET['route'];
// Handle different routes
if($route === 'route1') {
// Code for route 1
//echo json_encode(["message" => "Response from route 1"]);
// Make HTTP GET request
$response = file_get_contents($url, false, $context);
// Check if the request was successful
if ($response === false) {
// Handle error
echo json_encode(["error" => "Failed to fetch data"]);
} else {
// Output the response as JSON
header('Content-Type: application/json');
// Output the response
echo $response;
}
}
}
?>
这一切都可以在我的电脑上运行。现在,当我尝试将其实现到 WordPress 网站时,它不起作用。我认为我的问题是我的终点是错误的。我不知道如何指向 WordPress 子主题中的functions.php 文件。我怀疑这一点,因为我收到此错误:
Error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
在我的 javascript 代码中,我将基本 URL 更改为:
const baseURL = 'https://purgace.com/wp-content/themes/Divi%20Pledge%20Theme/functions.php';
在我的子主题functions.php文件中,我像这样实现我的代码:
<?php
function my_theme_enqueue_styles() {
$parent_style = 'divi-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
//my code for api call below:
$url = 'https://api.pledge.to/v1/organizations';
$api_key = {my_api_key};
//set headers
$context = stream_context_create([
'http' => [
'header' => "Authorization: Bearer $api_key\r\n"
]
]);
if(isset($_GET['route'])) {
$route = $_GET['route'];
// Handle different routes
if($route === 'route1') {
// Code for route 1
//echo json_encode(["message" => "Response from route 1"]);
// Make HTTP GET request
$response = file_get_contents($url, false, $context);
// Check if the request was successful
if ($response === false) {
// Handle error
echo json_encode(["error" => "Failed to fetch data"]);
} else {
// Output the response as JSON
header('Content-Type: application/json');
// Output the response
echo $response;
}
}
}
?>
有谁知道在我的 WordPress 子主题中调用functions.php 的端点应该是什么?任何帮助表示赞赏!谢谢!
您的“API”以 json 形式返回响应
header('Content-Type: application/json');
,然后您的 javascript 代码尝试解析该 json 并失败,因为您从第 3 方获得的当前响应是 HTML 响应而不是 json 响应。