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.

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料