【发布时间】:2019-12-19 10:48:23
【问题描述】:
我正在尝试从我服务器上的 PHP 文件创建的 JSON 响应中提取股票价格。我在下面描述了 2 个测试,测试 1 成功地从文件中提取 JSON 数据,测试 2。从服务器上的 PHP 脚本获取 JSON 数据会导致错误。我已经为此工作了很长时间,因此非常感谢您对获得解决方案的任何帮助,非常感谢。
我在客户端使用 Wordpress 和 Woody Universal Snippets,最终我会将代码集成到数据表脚本中。
测试 1. 从服务器上的文本文件中获取 JSON 数据工作 100% 以下
<script>
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings_json1.txt");
//ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
//ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
ourRequest.onload = function() {
console.log(ourRequest.responseText);
var ourDataJSON = JSON.parse(ourRequest.responseText);
}
ourRequest.send();
</script>
JSON 文件 ajax_stock_holdings_json1.txt
[
{
"symbol": "CTY.LSE",
"price" : "430"
}
]
测试 2. 失败 注释掉一行
ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings_json1.txt");
取消注释行
ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
在下面运行本地客户端脚本
<script>
var ourRequest = new XMLHttpRequest();
//ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings_json1.txt");
ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
//ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
ourRequest.onload = function() {
console.log(ourRequest.responseText);
var ourDataJSON = JSON.parse(ourRequest.responseText);
}
ourRequest.send();
</script>
服务器 PHP 文件
<?php
/* Loads the WordPress environment and template */
require( '../../wp-blog-header.php' );
global $current_user;
wp_get_current_user();
// DataTables PHP library
include( "../lib/DataTables.php" );
$json_array = array();
$stock_id = 709; // CTY.LSE
try {
$pdo = new PDO(strtolower($sql_details['type']) . ":host=" . $sql_details['host'] . ";dbname=" . $sql_details['db'], $sql_details['user'], $sql_details['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully" . "\n\n";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $pdo->query("SELECT id, symbol, name, price FROM dm_stocks WHERE id = $stock_id");
foreach ($result as $row) {
echo "" . $row['id'] . "";
echo " : " . $row['symbol'] . "";
echo " : " . $row['name'] . "";
echo " : " . $row['price'] . "\n";
array_push( $json_array, array('symbol'=>$row['symbol'], 'price'=>$row['price'] ) );
}
echo json_encode($json_array);
?>
结果是 ajax_stock_holdings1.php 网络响应
Connected successfully
709 : CTY.LSE : City of London Investment Trust Plc : 405.5
[{"symbol":"CTY.LSE","price":"405.5"}]
控制台日志
JQMIGRATE: Migrate is installed, version 1.4.1
(index):294 Connected successfully
709 : CTY.LSE : City of London Investment Trust Plc : 405.5
[{"symbol":"CTY.LSE","price":"405.5"}]
VM2786:1 Uncaught SyntaxError: Unexpected token C in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.ourRequest.onload ((index):295)
使用 PHP 的完整路径取消注释行
ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
导致以下错误
控制台显示
Access to XMLHttpRequest at 'https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php' from origin 'https://www.dividendlook.co.uk' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我尝试配置 HTTP 标头插件无济于事,这可能归结为无限数量的配置选项,知道如果有的话会清除我的错误。
我已将代码添加到我的服务器 PHP 文件以修复 Access-Control-Allow-Origin 问题,如下所示:-
<?php
/* Loads the WordPress environment and template */
require( '../../wp-blog-header.php' );
global $current_user;
wp_get_current_user();
// DataTables PHP library
include( "../lib/DataTables.php" );
// HTTP Header
header('Access-Control-Allow-Origin: https://dividendlook.co.uk');
$json_array = array();
$stock_id = 709; // CTY.LSE
...etc as before
Failed to load resource: the server responded with a status of 404 ()
jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE: Migrate is installed, version 1.4.1
(index):1 Access to XMLHttpRequest at 'https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php' from origin 'https://www.dividendlook.co.uk' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://divdendook.co.uk' that is not equal to the supplied origin.
generic-no-float.css:1 Failed to load resource: the server responded with a status of 404 ()
将下面一行替换为 PHP 文件,而不是用站点名替换前面的行
header('Access-Control-Allow-Origin: *');
导致错误
Failed to load resource: the server responded with a status of 404 ()
jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE: Migrate is installed, version 1.4.1
(index):294 Connected successfully
709 : CTY.LSE : City of London Investment Trust Plc : 405.5
[{"symbol":"CTY.LSE","price":"405.5"}]
(index):1 Uncaught SyntaxError: Unexpected token C in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.ourRequest.onload ((index):295)
generic-no-float.css:1 Failed to load resource: the server responded with a status of 404 ()
我在 .htaccess 的末尾添加了以下代码,它修复了 CORS 策略:“Access-Control-Allow-Origin”问题,现在错误是
''' 加载资源失败:服务器响应状态为 404 () jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE:已安装 Migrate,版本 1.4.1 (index):290 ourRequest.responseText >>>>>:[{"symbol":"CTY.LSE","price":"405.5"}]:
但是,客户端脚本正常读取 JSON
新建客户端脚本
<script>
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
ourRequest.onload = function() {
console.log("ourRequest.responseText >>>>>:"+ourRequest.responseText+":<<<<");
}
ourRequest.send();
</script>
【问题讨论】:
标签: javascript php json wordpress