2017-04-01 1 views
1

바코드를 쓰는 텍스트 입력이 있는데, 데이터베이스에서 이름과 가격을 반환합니다.JSON : getElementById가 Undefined를 반환합니다.

내 코드는 다음과 같습니다

보기 :

<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)이 있고 자바 스크립트 개체 (jsonObject)가 필요합니다. JSON.parse을 사용하여 JSON.stringify 대신 JSON 문자열을 JavaScript 객체로 변환하려고합니다. 역순으로 JavaScript 객체를 JSON 문자열로 변환합니다.

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

나는 그것을 시도,하지만 난'구문 에러 가지고 : JSON.parse : 콘솔에서 JSON의 data' 라인 1 열 (44)에서 JSON 데이터 후 예상치 못한 공백이 아닌 문자를하고 매번 나는 셀에 바코드 쓰기 div가 비어 있습니다. – Feralheart

+0

@Fheheheheart'this.responseText'의 정확한 값은 무엇입니까? – Frxstrem

관련 문제