gpt4 book ai didi

javascript - 将 undefined 分配给 JSON 属性值

转载 作者:行者123 更新时间:2023-12-01 00:20:57 27 4
gpt4 key购买 nike

我无法从在 WordPress 环境中运行的服务器返回的 JSON 中提取 JSON 属性值。

客户端通用 Woody 片段脚本

<html>
<body>

<h2>JSON string output from a JavaScript object.</h2>

<h4>JSON String Value is:</h4><p id="demo"> </p>
<h4>JSON Symbol2 Value is:</h4><p id="json_symbol2"> </p>
<h4>JSON Symbol Value is:</h4><p id="json_symbol"> </p>
<h4>JSON Price Value is:</h4><p id="json_price"> </p>

<script>
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings2.php");
ourRequest.onload = function() {
var obj = ourRequest.responseText;
var myJSON = JSON.parse(JSON.stringify(obj));
//var myJSONprice = JSON.parse(JSON.stringify(obj.price));
console.log( myJSON );

console.log( myJSON.symbol );
console.log(myJSON.price);

document.getElementById("demo").innerHTML = myJSON;
//document.getElementById("json_symbol2").innerHTML = myJSONprice;
document.getElementById("json_symbol").innerHTML = myJSON.symbol;
document.getElementById("json_price").innerHTML = myJSON.price;
}
ourRequest.send();
</script>
</body>
</html>

服务器 PHP 脚本

<?php

/*
* ajax_stock_holdings2.php
*/
$filename = 'ajax_stock_holdings2.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" );


//$stock_id = $_GET['stock_id']; // manually setting variable for testing
$stock_id = 1293;
$stock_array = array();

// check if variable is NOT blank pass JSON back to client
if ($stock_id <> "") {

//echo "the value of stock_id is :" . $stock_id . ":" . "\n";

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 $filename . "Connected successfully" . "\n\n";
}
catch(PDOException $e)
{
// echo $filename . "Connection failed: " . $e->getMessage();
}

$result = $pdo->query("SELECT id, symbol, name, price FROM dm_stocks WHERE id = $stock_id");
foreach ($result as $row) {

array_push( $stock_array, array('symbol'=>$row['symbol'], 'price'=>$row['price'] ) );
}

echo json_encode($stock_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

?>

返回 JSON

[
{
"symbol": "GSK.LSE",
"price": 1744
}
]

客户端脚本的输出

Test JSON
JSON string output from a JavaScript object.
JSON String Value is:
[ { "symbol": "GSK.LSE", "price": 1744 } ]

JSON Symbol2 Value is:
JSON Symbol Value is:
undefined

JSON Price Value is:
undefined

我尝试取消注释 Symbol2 的注释行,这会导致错误,即在 stringify 之前分配属性值

VM23451:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.ourRequest.onload ((index):303)

第 303 行是

var myJSONprice =   JSON.parse(JSON.stringify(obj.price));

非常感谢有关此问题的任何帮助,非常感谢科林

我正在尝试集成上述代码,以将价格作为消息写入 datatables.net 编辑器模式,客户端代码段摘录如下

    editor.dependent( 'dm_transactions.stock_id', function ( val, data, callback ) {
$.ajax( {
url: '../../Editor-PHP-1.9.0/controllers/ajax_stock_transactions.php',
dataType: 'json',
// pass stock_id value to server php script
data: { "stock_id": val },
success: function (json) {
callback(json);

ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_transactions.php");
ourRequest.onload = function() {
obj = ourRequest.responseText;
myJSONobj = JSON.parse(obj);
myJSONstr = JSON.parse(JSON.stringify(obj));

console.log( myJSONobj );
console.log( myJSONstr );

console.log(myJSONobj[0].symbol);
console.log(myJSONobj[0].price);

document.getElementById("json_obj").innerHTML = myJSONobj;
document.getElementById("json_str").innerHTML = myJSONstr;
document.getElementById("json_symbol").innerHTML = myJSONobj[0].symbol;
document.getElementById("json_price").innerHTML = myJSONobj[0].price;
}
ourRequest.send();

editor.field("dm_transactions.price").set(myJSONobj[0].price);
}),{
event: 'keyup change'
};

editor.dependent('dm_transactions.stock_id', function ( val, data, callback ){
return { messages: { 'dm_transactions.price': 'Yesterday Close : ' + myJSONobj[0].price }};

},{
event: 'keyup change'
});

生成的错误如下

(index):570 Uncaught TypeError: Cannot read property '0' of undefined
at (index):570
at HTMLDivElement.<anonymous> (dataTables.editor.js:2602)
at HTMLDivElement.dispatch (jquery-3.3.1.js:5183)
at HTMLDivElement.elemData.handle (jquery-3.3.1.js:4991)
at Object.trigger (jquery-3.3.1.js:8249)
at HTMLSelectElement.<anonymous> (jquery-3.3.1.js:8327)
at Function.each (jquery-3.3.1.js:354)
at jQuery.fn.init.each (jquery-3.3.1.js:189)
at jQuery.fn.init.trigger (jquery-3.3.1.js:8326)
at dataTables.editor.js:9159

行(索引):570 位于下方

editor.field("dm_transactions.price").set(myJSONobj[0].price);

对于如何将此代码集成到上面显示的数据表代码中的任何帮助,我们将不胜感激,谢谢 Colin

最佳答案

PHP 代码的响应是一个关联数组的数组,一旦 json_encoded 就变成一个对象数组。因此,要访问单个值,您需要迭代数组,或者,如果查询仅返回一行,您可以简单地使用 [0] 元素,例如

console.log(myJSON[0].symbol);
console.log(myJSON[0].price);

关于javascript - 将 undefined 分配给 JSON 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59435918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com