以下脚本表示跨域,并为选择菜单提取JSON结果。当前,CURL能够回显$ result,但无法在选择菜单中显示,并带有控制台日志错误:Uncaught ReferenceError:未定义$ result。我需要诊断此事的帮助。
<?php
$data_string = json_encode($data,JSON_UNESCAPED_SLASHES);
$ch = curl_init('https://xxxxxxx.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
echo($result);
?>
<script>
let dropdown = $('#title-dropdown');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose Title</option>');
dropdown.prop('selectedIndex', 0);
const url = $result;
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.description).text(entry.display_name));
})
});
</script>
答案 0 :(得分:0)
您没有将PHP $ result变量输出到Javascript,而是在告诉javascript查找不存在的变量。试试
const url = '<?php echo $result ?>';
自从我完成任何PHP以来已经有一段时间了,但是如果它不是100%正确的话,那至少应该使您走上正确的轨道。
答案 1 :(得分:-1)
更改此
const url = $result;
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.description).text(entry.display_name));
})
});
对此:
const json = $.parseJSON('<?php echo $result; ?>');
var result = json.result;
for (var i = 0; i < result.length; i++) {
for (var key in result[i]) {
console.log('KEY: ' + key + 'VALUE: ' + result[i][key]);
}
}