2016-08-14 2 views
0

다음은 코드입니다. PHP를 사용하여 데이터베이스에서 데이터를 검색하고 원시 자바 스크립트를 사용하고 싶습니다. 화면에 오류가 나타나지 않지만 결과가 div 요소에 표시되지 않습니다 .Kindly 여기서 무엇이 잘못되었는지 알려주세요.PHP와 아약스 통신이 작동하지 않습니다.

HTML 코드 :

<!DOCTYPE HTML> 
<html> 
<head> 
</head> 
<body> 
    User<input type="text" name="enterText" id="enterText"> 
    <input type="button" value="click" id="btn"> 
    <div id="dvID"></div> 
    <script src="sendData.js"></script> 
</body> 
</html> 

자바 스크립트 코드 :

<?php 
$dbhost = "localhost"; 
$username = "root"; 
$password = ""; 
mysql_connect($dbhost,$username,$password); 
@mysql_select_db("trynew") or die(mysql_error()); 

if (isset($_POST["enterText"])) { 
$user = $_POST['enterText']; 
echo $user; 
} 
$query = "SELECT * FROM trynewtable where name = '$user' "; 
$result = mysql_query($query); 
if($result==FALSE) 
{ 
die(mysql_error()); 
} 

$row = mysql_fetch_array($result); 
$jsondata = json_encode($row); 
echo $jsondata; 
mysql_close(); 
?> 

내가 모두 시도 :

var xhr; 

if(window.XMLHttpRequest) 
{ 
xhr = new XMLHttpRequest(); 
} 
else 
{ 
xhr = new ActiveXObject('Microsoft.XMLHTTP'); 
} 
var jsonData= ""; 
xhr.onreadystatechange =function() 
{ 
    if(xhr.readystate==4) 
{ 
    console.log("in ready state"); 
    if(xhr.success >=200&& xhr.success <300) 
    { 
     consle.log("in sucess"); 
     jsonData = JSON.parse(xhr.responseText); 
     document.getElementIdById("dvID").innerHTML = jsonData; 
     console.log("after jsonData "+jsonData); 
    } 
    else 
    { 
     document.getElementIdById("dvID").innerHTML = "it's not success "; 
    } 
    } 
} 
var element1 = document.getElementById("dvID") ; 
console.log(element1); 
xhr.open("POST","index.php"); 
var element = document.getElementById("btn") ; 
if(element) 
{ 
element.addEventListener('click',function(){ 
console.log("just clicked") 
xhr.send(document.getElementById("dvID").value); 

}) 여기 }

및 내 PHP 코드입니다 게시하다 그리고 GET 방법은 작동하지만 아무것도 작동하지 않습니다.

내가 php "xhr.send (document.getElementById ("enterText "). value);로 보내는 데이터를 변경하는 버그가있었습니다." 아약스 기능 당신이`사용해야합니다 (있는 경우 xhr.readyState == -하지만 여전히

+0

작은 약간의 오류가 없다 4 && xhr.status == 200) {'xhr.success'가 아니라''''mysqli' 또는''PDO'로 바꾸고, 재사용 가능한 ajax 함수를 만드는 것이 좋습니다. 모든 것을 다시 작성하기보다는 사용 된 매개 변수를 변경하여 다른 용도로 사용할 수 있습니다. – RamRaider

+0

"@mysql_select_db()", PHP에서 그럴 경우 해당 없음 –

+0

그리고 Theres no "enterText"가 PHP에 게시되었습니다 –

답변

0

당신이 재사용 아약스 기능과 mysqli를 시작하는 화면에 아무것도

<?php 
    if($_SERVER['REQUEST_METHOD']=='POST'){ 

     if(!empty($_POST['enterText'])){ 
      ob_clean(); 

      /* empty placeholder array for json data */ 
      $output=array(); 

      $text=$_POST['enterText']; 

      /* db connection using mysqli */ 
      $dbhost = 'localhost'; 
      $dbuser = 'root'; 
      $dbpwd = 'xxx'; 
      $dbname = 'trynew'; 

      /* create the connection */ 
      $db = new mysqli($dbhost, $dbuser, $dbpwd, $dbname); 

      /* create the sql with a placeholder rather than embedded variables! */ 
      $sql='select * from `trynewtable` where `name`=?;'; 


      $stmt=$conn->prepare($sql); 
      $stmt->bind_param('s', $text); 
      $res=$stmt->execute(); 

      if($res){ 
       /* Bind EACH field referenced in query and in recordset here!!! */ 
       $stmt->bind_result($id, $user); 
       /* Number of fields in recordset = number of bound variables! */ 

       /* Fetch the data */ 
       $stmt->fetch(); 

       /* Add data to output - to be sent as json data */ 
       $output=array( 
        'id'  => $id, 
        'username' => $user 
       ); 
      } 
      /* tidy up */ 
      $stmt->free_result(); 
      $stmt->close(); 
      $db->close(); 

      /* send the response to the ajax callback function */ 
      header('Content-Type: application/json', true, 200); 
      exit(json_encode($output)); 
     } 


    } 

?> 

<!DOCTYPE HTML> 
<html> 
    <head> 
     <title>Got to have a title</title> 
     <script type='text/javascript'> 

      /* basic reusable ajax function */ 
      function ajax(m,u,p,c,o){ 
       /* 
        m=method,u=url,p=params {n:v},c=callback,o=options {n:v} 
       */ 
       var xhr=new XMLHttpRequest(); 
       xhr.onreadystatechange=function(){ 
        if(xhr.readyState==4 && xhr.status==200)c.call(this, xhr.response, o, xhr.getAllResponseHeaders()); 
       }; 

       var params=[]; 
       for(var n in p)params.push(n+'='+p[n]); 

       switch(m.toLowerCase()){ 
        case 'post': 
         p=params.join('&'); 
        break; 
        case 'get': 
         u+='?'+params.join('&'); 
         p=null; 
        break; 
       } 

       xhr.open(m.toUpperCase(), u, true); 
       xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
       xhr.send(p); 
      } 


      /* create instance of the ajax function */ 
      function bindEvents(e){ 
       document.getElementById('btn').addEventListener('click', function(){ /* this is where you set the different parameters, here we POST `enterText` */ 
        ajax.call(this, 'post', document.location.href, { enterText:document.getElementById('enterText').value }, callback, { dvID:document.getElementById('dvID') }) 
       }, false); 
      } 

      /* callback function to process response from PHP script */ 
      function callback(r,o,h){ 
       if(r){ 
        /* */ 
        var json=JSON.parse(r); 

        /* use the callback to process the json data */ 
        o.dvID.innerHTML='Response:'+r; 
       } 
      } 

      /* bind event listeners */ 
      document.addEventListener('DOMContentLoaded', bindEvents, false); 
     </script> 
    </head> 
    <body> 
     User: <input type="text" name="enterText" id="enterText"> 
     <input type="button" value="click" id="btn"> 
     <div id="dvID"></div> 
    </body> 
</html> 
관련 문제