首页 > 解决方案 > 未捕获的 ReferenceError:$result 未定义

问题描述

以下脚本表示跨域并为选择菜单提取 JSON 结果。目前 CURL 能够回显 $result 但无法在选择菜单中显示控制台日志错误:Uncaught ReferenceError: the $result is not defined。我需要帮助来诊断这件事。

<?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>

标签: javascriptphpjson

解决方案


您没有将 PHP $result 变量输出到 Javascript,而是告诉 javascript 查找不存在的变量。尝试

const url = '<?php echo $result ?>';

自从我完成任何 PHP 以来已经有一段时间了,但如果它不是 100% 正确,那至少应该让你走上正确的轨道。


推荐阅读