在服务器端处理远程请求时,file_get_contents() 函数似乎是一个可靠的选择,但 WordPress 已经包含一个非常有用的 API,称为 HTTP API。
HTTP API 可用于向远程 API 发送数据和从远程 API 检索数据,这也意味着对您自己的服务器的任何请求。
WordPress 中的 HTTP API 有四个主要功能:
例如,您可以使用 wp_remote_get() 从 network.json 文件中检索数据,然后将其与 wp_localize_script() 一起解析strong> 函数,将您需要的数据暴露给入队的 js 文件。
请参考以下功能(未经测试),但您应该没有任何问题。
-- 函数--
function wp_request_localize_my_json_data() {
// Helpers to define the $url path
//$protocol = is_ssl() ? 'https' : 'http';
$directory = trailingslashit( get_template_directory_uri() );
// Define the URL
$url = $directory . 'network.json';
// Register main js file to be enqueued
wp_register_script( 'network-js', $directory . 'assets/js/network.js', array('jquery'), false, true );
// Make the request
$request = wp_remote_get( $url );
// If the remote request fails, wp_remote_get() will return a WP_Error, so let’s check if the $request variable is an error:
if( is_wp_error( $request ) ) {
return false; // Bail early
}
// Retrieve the data
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
// Localize script exposing $data contents
wp_localize_script( 'network-js', 'networkJSON', array(
'network_url' => admin_url( 'admin-ajax.php' ),
'full_data' => $data
)
);
// Enqueues main js file
wp_enqueue_script( 'network-js' );
}
add_action( 'wp_enqueue_scripts', 'wp_request_localize_my_json_data', 10);
如果一切顺利,您最终可能会得到从 network.json 文件中检索到的本地化数据供您使用。
现在假设您在 network.json 文件中有一个名为 current_user 的变量。因此,为了在排队的 JS 文件中访问此变量,您只需执行以下操作:
<script type="text/javascript">
var my_data = networkJSON.full_data;
var user = my_data.current_user;
</script>