从服务器 PHP 数组中提取 JSON 数据时出现问题



我正在尝试从服务器上的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" . "nn"; 
}
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文件中,以将访问控制允许源问题修复如下:-

<?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策略:"访问控制允许来源"问题,现在错误是

''' 无法加载资源:服务器以状态 404 (( 响应 jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE:已安装迁移,版本 1.4.1 (索引(:290 ourRequest.responseText>>>>>:[{"symbol":"CTY.伦敦证券交易所","价格":"405.5"}]:<<<<泛型无浮点数.css:1 无法加载资源:服务器响应状态为 404 (( '''

但是,客户端脚本正在读取 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>

在您的服务器上,PHP。添加这些必需的标头。浏览器拒绝来自不同来源的响应。要获得此工作,请将访问控制允许原点设置为"*"。这是来自任何来源的任何请求都会得到响应。

最新更新