2014-01-25 3 views
0

아래 스크립트는 http://www.w3schools.com/php/php_ajax_database.asp에 있습니다. 그러나 나는 이것을 wordpress를 통해 구현하기가 어려웠다. 이것은 localhost에서 완벽하게 작동하지만 wordpress에서는 실패했다. 나는 이미 동일한 프로세스로 검색을 수행했지만 아직 파악할 수 없습니다. Wordpress를 통해 ajax 스크립트를 호출하는 방법에 대한 단계별 프로세스를 요청할 수 있습니까?wordpress ajax - AJAX를 사용하여 데이터베이스에서 정보를 가져옵니다.

** 내 사용자 지정 FrontPage를 * *

<?php 
/* 
Template Name: Custom Template 
*/ 
?> 
<?php 
/** 
* The template for displaying all pages. 
* 
* This is the template that displays all pages by default. 
* Please note that this is the WordPress construct of pages 
* and that other 'pages' on your WordPress site will use a 
* different template. 
* 
* @package WordPress 
* @subpackage Twenty_Eleven 
* @since Twenty Eleven 1.0 
*/ 

get_header(); ?> 
<script> 
function showUser(str) 
{ 
if (str=="") 
    { 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
    } 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","getuser.php?q="+str,true); 
xmlhttp.send(); 
} 
</script> 
     <div id="primary"> 
      <div id="content" role="main"> 

<form> 
<select name = "users" onChange = "showUser(this.value)"> 
         <?php 
          include 'dbconfig.php'; 
          $result=mysql_query("SELECT DISTINCT lastname FROM people ORDER BY lastname ASC;"); 
          echo '<option value="">' . 'Select an Agent' . '</option>'; 

          while ($row=mysql_fetch_array($result)) 
           { 
           echo '<option value="' . $row['lastname'] . '">' . $row['lastname'] . '</option>'; 
           } 
         ?> 
         </select> 
</form> 
<br> 
<div id="txtHint"><b>Person info will be listed here.</b></div> 

      </div><!-- #content --> 
     </div><!-- #primary --> 

<?php get_footer(); ?> 

PHP 파일 (getuser.php)

<?php 
$q = intval($_GET['q']); 

include 'dbconfig.php'; // PHP File to login credentials 
$sql="SELECT * FROM people WHERE id = '".$q."'"; 

$result = mysql_query($sql); 

echo "<table border='1'> 
<tr> 
<th>Firstname</th> 
<th>Lastname</th> 
<th>Age</th> 
<th>Hometown</th> 
<th>Job</th> 
</tr>"; 

while($row = mysql_fetch_array($result)) 
    { 
    echo "<tr>"; 
    echo "<td>" . $row['FirstName'] . "</td>"; 
    echo "<td>" . $row['LastName'] . "</td>"; 
    echo "<td>" . $row['Age'] . "</td>"; 
    echo "<td>" . $row['Hometown'] . "</td>"; 
    echo "<td>" . $row['Job'] . "</td>"; 
    echo "</tr>"; 
    } 
echo "</table>"; 

mysql_close($con); 
?> 

<?php 
$q = intval($_GET['q']); 

include 'dbconfig.php'; // PHP File to login credentials 
$sql="SELECT * FROM people WHERE id = '".$q."'"; 

$result = mysql_query($sql); 

echo "<table border='1'> 
<tr> 
<th>Firstname</th> 
<th>Lastname</th> 
<th>Age</th> 
<th>Hometown</th> 
<th>Job</th> 
</tr>"; 

while($row = mysql_fetch_array($result)) 
    { 
    echo "<tr>"; 
    echo "<td>" . $row['firstname'] . "</td>"; 
    echo "<td>" . $row['lastname'] . "</td>"; 
    echo "<td>" . $row['age'] . "</td>"; 
    echo "<td>" . $row['hometown'] . "</td>"; 
    echo "<td>" . $row['job'] . "</td>"; 
    echo "</tr>"; 
    } 
echo "</table>"; 

mysql_close($con); 
?> 

액션 촬영 : 변환 (인 getUser. php)를 함수로 추가 한 다음 functions.php 테마에 추가하십시오. wp add_action hook.please를 호출하십시오. 아래 참조하십시오.

function getuser(){ 
    //get the data from ajax() call 
    //copied script from getuser.php 
    } 
    // creating Ajax call for WordPress 
    add_action('wp_ajax_nopriv_getuser', 'getuser'); 
    add_action('wp_ajax_getuser', 'getuser'); 

여러분의 도움을 많이드립니다. 감사합니다.

+0

[이 답변보기] (http://stackoverflow.com/questions/20831673/send-a-form-from-jquery-to-php-with-ajax-wordpress/20831780#20831780)을 통찰력을 얻을 수 있습니다. – Ohgodwhy

답변

0

첫 번째 문제는 해결하기 : 당신이 functions.php 사람들을 쓴 것처럼 다음 functions.php에서 기능을 실행할 수있는 관리자 - ajax.php에서

그 ADD_ACTION의 이동을,이 나타 납니까? 이는 클라이언트가 아약스를 마주 치는 경우에도 마찬가지입니다.

몇 가지 다른 점 :

는 클라이언트 측에서 물건을 단순화하기 위해 적어도 처음에는 JQuery와 또는 아약스 라이브러리를 사용하는 것이 좋습니다.

훌륭한 JSON API를 여기에서 사용하는 것을 고려하십시오 : http://wordpress.org/plugins/json-api/, 나는 방대한 양의 wp ajax 함수를 수동으로 작성한 후 라이브러리가 훨씬 적은 작업을 위해 모든 것을 처리한다는 것을 발견했습니다.

편집 : 여기

는 각도의 $ HTTP를 방법과 위의 JSON-API 라이브러리를 사용하여 내 웹 사이트에서 방법의 예입니다. 이 예에서는 사용자 지정 특성 및 값이 지정된 최신 3 개의 게시물을 가져오고 일부 데이터 만 반환하여 (대역폭을 절약하기 위해).

var baseUrl = http://localhost:3000 // Your Site Url Here 

$http({ 
     method:'GET', 
     url:baseUrl, 
     params:{ 
      json:'get_posts', 
      count:3, 
      include:'excerpt,thumbnail,title,slug,date,categories', 
      meta_key: 'featured', 
      meta_value: 'projects_yes' 
     } 
    }) 
     .success(function(data, status, headers, config){ 
      console.log(data); 
     }) 
     .error(function(data,status,headers,config){ 
      console.log(data,',\n', status, headers, config); 
     }); 
+0

Adul에게 감사의 말씀을 전합니다. Ajax 라이브러리를 사용하여 어떻게하는지, 또는 어떤 방법 으로든 작동하는 방법을 내게 보여줄 수 있습니까? 사실, 나는 PHP에 익숙하지 않은, 그냥 스크립트를 연결하는 방법을 학습 wordpress. 더 많은 권력! – AbeDupa

+0

각도 및 위의 라이브러리 예제가 포함되도록 수정되었습니다. 며칠을 보냈고 아약스로 Wordpress 데이터를 호출하는 가장 쉬운 방법은 얼마나되는지 충분히 강조하지 못했습니다. –

관련 문제