douzhi3667 2019-05-15 16:08
浏览 47
已采纳

未定义的返回值[重复]

This question already has an answer here:

I want to get data from a MySQL-database using JS and PHP (without jquery or ajax) But I keep getting the "undefined Return Value Error".

It's my first time programming in JS and PHP.

url: "../PHP/Kassensystem.php?productname="+productname

JS:

function getProduct(url) {

let product;

var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = function () {
    if (request.status == 200) {
        product = request.responseText;
    }
};
request.send(null);

return product;
}

PHP:

<?php
$productname = $_GET['productname'];
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'allgolddb';

$conn = mysqli_connect($servername, $username, $password, $dbname);
$prodctInfos = array();

$sql = "SELECT * FROM products WHERE name = '$productname'";

$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
  $prodctInfos[] = $row;
}

$json_array = json_encode($prodctInfos);
return $json_array;
?>
</div>
  • 写回答

1条回答 默认 最新

  • 普通网友 2019-05-15 16:49
    关注

    In your open method you've set 3rd param to true so your request.send will be executed asynchronously. And as with every asynchronous JavaScript, by the time your code execution reaches return product product is still undefined and hence the error.

    You can set the 3rd param to false to make it synchronous and your code will work (atleast working in firefox so far):

    request.open("GET", url, false);
    

    However the sync option is deprecated. From MDN

    Synchronous requests on the main thread can be easily disruptive to the user experience and should be avoided; in fact, many browsers have deprecated synchronous XHR support on the main thread entirely. Synchronous requests are permitted in Workers.

    As for working asynchronously, you'll have to consume within the callback to onload method:

    request.onload = function () {
      if (request.status == 200) {
        product = request.responseText;
        console.log(product) // consume here
      }
    };
    

    You could also use Promise, optionally with async/await. More here to work with asynchronous code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分