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

标签 javascript php json wordpress

我正在尝试从服务器上的 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 headers 插件但无济于事,这可能是由于无数的配置选项,知道哪些(如果有的话)会清除我的错误。

我已将代码添加到我的服务器 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:迁移已安装,版本 1.4.1 (索引):290 ourRequest.responseText >>>>>:[{"symbol":"CTY.LSE","price":"405.5"}]:<<<< generic-no-float.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。添加那些必需的 header 。浏览器拒绝来自不同来源的响应。要实现此功能,请将 Access-Control-Allow-Origin 设置为“*”。这是来自任何来源的任何请求都会得到响应。

关于javascript - 从服务器 PHP 数组中提取 JSON 数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408146/

相关文章:

javascript - 如何使用 Kendo UI Grid 的 SetDataSource 方法

javascript - 使用表构建的 Jquery Accordion 菜单

javascript - props 验证中缺少功能组件 eslint 'date'

php - 如何使 PHP if 语句依赖于 SQL 查询结果

java - 解析 JSON 时出现问题

javascript - 如何将 api 添加到 Visual Studio Code

php多线程

javascript - 检查 session 上的 isset 会停止 javascript

android - 检索 JSON 对象时出现空指针异常

java - 提取特定的 json 数组元素比较所有数组元素