2017-04-01 90 views
1

我有一個文本輸入,我寫條形碼時會返回數據庫中的名稱和價格。JSON:getElementById返回未定義

我的代碼如下所示:

查看:

<script> 
function showProduct(str) { 
    if (str == "") { 
     document.getElementById("txtHint").innerHTML = ""; 
     return; 
    } else { 
     if (window.XMLHttpRequest) { 
      // code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp = new XMLHttpRequest(); 
     } 
     xmlhttp.onreadystatechange = function() { 
      if (this.readyState == 4 && this.status == 200) { 
       console.log(this.responseText); 
       var jsonObject = JSON.stringify(this.responseText); 
       document.getElementById("nameHint").innerHTML = jsonObject["name"]; 
       document.getElementById("priceHint").innerHTML = jsonObject["price"]; 
} 
     }; 
     xmlhttp.open("GET","/getproduct/q="+str,true); 
     xmlhttp.send(); 
    } 
} 
</script> 
{{ Form::open() }} 
{{Form::text('barcode', null, ['onchange'=>"showProduct(this.value)"])}} 
<div id="nameHint></div> 
<div id="priceHint></div> 
{{Form::close}} 

控制器:

public function getProduct($id){ 
    ini_set('display_errors', 1);error_reporting(E_ALL); 

    $sql = DB::select('select * from inventory where barcode = ?', [$id]); 
    $name = $sql[0]->name; 
    $price= $sql[0]->price; 

    echo json_encode(array("name"=>$name, "price"=>$price)); 
} 

當我寫的條碼它表明:undefined在那裏,它必須證明名稱和價格。我錯過了什麼?

回答

2

你有一個JSON字符串(this.responseText),你想要一個JavaScript對象(jsonObject)。您想要使用JSON.parse,它將一個JSON字符串轉換爲JavaScript對象,而不是JSON.stringify,這反過來將JavaScript對象轉換爲JSON字符串。

var jsonObject = JSON.parse(this.responseText); 
       // ^-- here 
+0

我試過,但我得到了'語法錯誤:JSON.parse:在控制檯中的JSON data'行1列44意想不到的非空白字符後JSON數據,每次我寫在細胞中的條形碼div是空的 – Feralheart

+0

@Feralheart'this.responseText'的確切值是什麼? – Frxstrem