【问题标题】:Can't retrieve element from array using XMLHttpRequest无法使用 XMLHttpRequest 从数组中检索元素
【发布时间】:2019-04-12 23:11:30
【问题描述】:

无法从 XMLHttpRequest 访问数组中的元素。

我有一个名为 findProductDetails 的函数,我在其中传入一个 productName,它是我的数据库中的主键。我使用 XMLHttpRequest 通过来自 productSearch.php 的响应来检索数组。我可以在 for 循环内完美地打印 itemsList。但我尝试返回数组,我可以将它打印到控制台,它会显示它的长度为 0,我可以看到元素,但无法将它们单独检索为数组 [n]。

 function findProductDetails(productName){
      //Store results      
      var array = []

      xmlhttp=new XMLHttpRequest();
      xmlhttp.onreadystatechange=function() {

           if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                if (xmlhttp.responseText) {
                    var itemsList = xmlhttp.responseText.split(",");
                    for(var i = 0; i < itemsList.length; i++) {
                        array[i] = itemsList[i];
                    }        
                }
           }
      }

      xmlhttp.open("GET","productSearch.php?name=" + productName,true);
      xmlhttp.send();

      return array;
  }

发生了什么事?

【问题讨论】:

  • 你能 console.log responseText 吗?
  • @Elanochecer From console.log(xmlhttp.responseText.split(",")); 它打印我想要的,一个长度为 4 个元素的数组。
  • 哦,你不能在响应到达之前返回数组。把函数变成一个承诺。最简单的方法是只使用 jquery ajax 函数。 api.jquery.com/jquery.ajax
  • @Elanochecer 谢谢!让它工作。

标签: javascript php xmlhttprequest


【解决方案1】:

我的解决方案:

function request(method, url) {
     return new Promise(function (resolve, reject) {
           var xhr = new XMLHttpRequest();
           xhr.open(method, url);
           xhr.onload = resolve;
           xhr.onerror = reject;
           xhr.send();
     });
}

然后,每当我想通过 php 文件通过回显结果从数据库中检索数据时,我都会调用它。

 request("GET", "productSearch.php?name=" + productName,true)
       .then(function (e) {
            //Results      
            var res = e.target.response;

        }, function (e) {
          // handle errors
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多