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

时间:2019-12-19 10:48:23

标签: javascript php json wordpress

我正在尝试从服务器上PHP文件创建的JSON响应中提取股票价格。我在下面描述了2个测试,测试1成功地从文件中提取了JSON数据,测试2。从服务器上的aPHP脚本获取JSON数据会导致错误。我从事此工作已有很长时间了,因此,非常感谢获得解决方案的任何帮助,谢谢。

我在客户端上使用Wordpress和Woody Universal Snippets,最终我将在工作后将代码集成到datatables脚本中。

测试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>

1 个答案:

答案 0 :(得分:1)

在您的服务器上,PHP。添加那些必需的标题。浏览器拒绝来自不同来源的响应。要完成这项工作,请将Access-Control-Allow-Origin设置为“ *”。这是来自任何来源的任何请求都会得到响应。