搜索无法在前端

时间:2017-10-13 20:48:47

标签: javascript php json

我刚刚在我的网站上用ajax创建了一个搜索选项,数据来自一个文本文件。我在PHP api中处理了搜索,它完成了这项工作,但问题是在前端显示此搜索结果。这不起作用,所以我需要你的帮助吗?

我的搜索PHP api:

<?php

//DATA coming from the browser
$sSearch = $_GET['search'];
//TURN it into UPPERCASE
strtoupper( $sSearch );

//GETTING FROM FILE:
$sajProducts = file_get_contents( 'products.txt' );
$ajProducts = json_decode( $sajProducts );

$matchfound = false;
//LOOPING THROUGH THE ARRAY OF PRODUCTS
for ( $i=0; $i< count( $ajProducts ); $i++ ) {

    if ( $sSearch == $ajProducts[$i]->name ) {
         $jSearchResult = $ajProducts[$i];
         $matchfound = true;    
         break;
    }
}
//if there is a match display the product
if ( $matchfound ) {
    echo json_encode ( $jSearchResult );
    exit;
}
//if not display ALL products
else { 

     echo json_encode( $ajProducts );
     exit;
}

?>

我的JAVASCRIPT位:

  txtSearchProducts.addEventListener("keyup", function() {

  var sSearch = document.getElementById("txtSearchProducts").value;
  console.log( sSearch );
  var sSearchUpperCase = sSearch.toUpperCase();        
  var sUrl = "api_search_products.php?search=" + sSearchUpperCase;

  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
      if ( this.readyState == 4 && this.status == 200 ) { 
           ajProductDataFromServer = JSON.parse( this.responseText );
           console.log( "Response:" + ajProductDataFromServer );



           if ( sessionStorage.getItem('role') === "admin" ) { 

                showProductAdmin();
                console.log ("SEARCH FOUND");

          } else {

                showProduct();
                console.log ("SEARCH FOUND");

          }


      }
  } 

  request.open( "GET", sUrl, true );
  request.send();

});

它确实构成了ajProductData =一个JSON对象,如果我将其字符串化,那么我可以看到它是正确的,所以这意味着我的serach工作,但是它不会在屏幕上显示任何内容。所以我怀疑问题可能与我尝试显示的方式有关,这与ShowProductAdmin();或Showproduct(); 包含的内容你可以看到它:

// DISPLAY PRODUCTS for ADMIN dinamically using a loop and then INSERT into HTML

  function showProductAdmin() {

      lblProductList.innerHTML = "";

      for ( var i = 0; i < ajProductDataFromServer.length; i++ ) {

          var lblProduct = '<div class="lblProduct">' + '<img src="' + ajProductDataFromServer[i].image + '"width="85%" alt="product" class="lblProductImage" data-productImage="' + ajProductDataFromServer[i].image + '">' + '<h3 class ="lblProductName" data-productName="' + ajProductDataFromServer[i].name + '" >' + ajProductDataFromServer[i].name + '</h3>' + '<h3 class ="lblProductPrice" data-productPrice="' + ajProductDataFromServer[i].price + '">' + 'Price:' + ' ' + ajProductDataFromServer[i].price + '<h3 class ="lblProductQuantity" data-productQuantity="' + ajProductDataFromServer[i].quantity + '">' + 'Quantity:' + ' ' + ajProductDataFromServer[i].quantity + '</h3>' + '<button id="btnEditProductBody" class="btnShowPage btnEditProduct" data-showThisPage="pageUpdateProduct" data-productId="' + ajProductDataFromServer[i].id + '">' + 'EDIT PRODUCT' + '</button>' + '<button class="btnDeleteProduct" data-productId="' + ajProductDataFromServer[i].id + '" >' + 'DELETE PRODUCT' + '</button>' + '<h3 class="lblErrorMessage" id="lblDeleteProductErrorMessage">' + '</h3>' + '</div>';

          lblProductList.insertAdjacentHTML( 'beforeend', lblProduct );
          showPages();

      }

  }



 // DISPLAY PRODUCTS for USER / PUBLIC dinamically using a loop and then INSERT into HTML

  function showProduct() {
      lblProductList.innerHTML = "";

      for ( var i = 0; i < ajProductDataFromServer.length; i++ ) {

          var lblProduct = '<div class ="lblProduct">' + '<img src="' + ajProductDataFromServer[i].image + '" width="85%" alt="product">' + '<h3 class ="lblProductName">' + ajProductDataFromServer[i].name + '</h3>' + '<h3 class ="lblProductPrice">' + 'Price:' + ' ' + ajProductDataFromServer[i].price + '<h3 class ="lblProductQuantity">' + 'Quantity:' + ' ' + ajProductDataFromServer[i].quantity + '</h3>' + '<button class="btnBuyProduct" data-productId="' + ajProductDataFromServer[i].id + '" >' + 'BUY PRODUCT' + '</button>' + '</div>';

          lblProductList.insertAdjacentHTML( 'beforeend', lblProduct );
      }

  }

然而在其他情况下,例如当我显示所有产品时,它工作正常: 请参阅此处的示例:

// GET ALL PRODUCTS and display them with diffrent features according role

  function getajProductData() {

      var request = new XMLHttpRequest();
      request.onreadystatechange = function() {
          if ( this.readyState == 4 && this.status == 200 ) {

              ajProductDataFromServer = JSON.parse( this.responseText );
              console.log( "Response:" + ajProductDataFromServer );

              if ( sessionStorage.getItem('role') === "admin" ) { 
                  console.log( "PRODUCTS ARE EDITABLE" );
                  showProductAdmin();

              } else if ( sessionStorage.getItem('role') === "user" ) {
                  console.log( "PRODUCTS ARE AVAILABLE FOR USER" );
                  showProduct();

              } else {
                  console.log( "PRODUCTS AVAILABLE FOR PUBLIC" );
                  showProduct();
              }

          }
      }

      request.open( "GET", "api_get_products.php", true );
      request.send();

  }

HTML,我也使用getajProductData()初始化所有产品;

!-- PRODUCTS display and editing is handled here according USER or ADMIN-->

    <div id="pageViewProducts" class="page">
            <div class="lblWrapper"> 
                  <button type="button" class="btnShowPage" id="btnCreateProduct" data-showThisPage="pageCreateProduct"><i class="fa fa-plus"></i>&nbsp;Add Product</button>
                  <form id="frmSortBy">
                    <p>Sort by:</p>
                    <select id="sortProductsSelector">
                      <option value="oPriceLowToHigh">PRICE (LOW TO HIGH)</option>
                      <option value="oPriceHighToLow" >PRICE (HIGH TO LOW</option>
                      <option value="oOnSale" id="oOnSale" selected>ON SALE</option>
                    </select>
                  </form>
                  <div id="lblProductList">
                    <!-- Generated dynamically -->
                  </div>
            </div>
    </div>

可能是干扰吗?

我的users.txt文件:

[
    {
        "role": "admin",
        "id": "59df4ef2d8d39",
        "email": "a@a.dk",
        "name": "A",
        "lastname": "A",
        "password": "1",
        "image": "img_webshop\/userimage-59dfb91515810.png"
    },
    {
        "role": "user",
        "id": "59df4f1b070e6",
        "phonenumber": "12345678",
        "name": "B",
        "lastname": "B",
        "password": "2",
        "image": "img_webshop\/userimage-59df8c0317707.png"
    },
    {
        "role": "user",
        "id": "59dfc0cb07985",
        "email": "c@c.dk",
        "name": "C",
        "lastname": "C",
        "password": "3",
        "image": "img_webshop\/userimage-59dfc0cb06c5f.png"
    },
    {
        "role": "user",
        "id": "59dfc22f26f78",
        "phonenumber": "87654321",
        "name": "D",
        "lastname": "D",
        "password": "4",
        "image": "img_webshop\/userimage-59dfc22f2638d.png"
    },
    {
        "role": "user",
        "id": "59dfc460b261e",
        "email": "e@e.dk",
        "name": "E",
        "lastname": "E",
        "password": "5",
        "image": "img_webshop\/userimage-59dfc460af866.png"
    }
]

我搜索的是每个对象的名称,所以如果我在搜索栏中输入A,我应该只看到名为A的JSON对象,依此类推。通常情况下,所有产品都显示为我之前提到的getajUserData(); 我希望它是明智的。

1 个答案:

答案 0 :(得分:0)

经过研究,我发现问题实际上是在api中,并且由于没有正确显示前端,所以现在这里是纠正的api,我在帖子的开头发布了。现在纠正这个整个叠加工作正常。

 <?php

    //DATA coming from the browser
    $sSearch = $_GET['search'];
    //TURN it into UPPERCASE
    strtoupper( $sSearch );

    //GETTING FROM FILE:
    $sajProducts = file_get_contents( 'products.txt' );
    $ajProducts = json_decode( $sajProducts );

    $matchfound = false;
    $jSearchResult = array();
    //LOOPING THROUGH THE ARRAY OF PRODUCTS
    for ( $i=0; $i< count( $ajProducts ); $i++ ) {

        if ( $sSearch == $ajProducts[$i]->name ) {
             $jSearchResult[] = $ajProducts[$i];
             $matchfound = true;    
        }
    }
    //if there is a match display the product
    if ( $matchfound ) {
        echo json_encode ( $jSearchResult );
        exit;
    }
    //if not display ALL products
    else { 

         echo json_encode( $ajProducts );
         exit;
    }

    ?>