2013-06-19 2 views
0

PHP와 XML을 사용하는 웹 페이지를 만드는 데는 비교적 새로운 편이지만 W3S Schools에서 보았던 somthine에 관심이 있습니다. 예제 페이지에서 보여주는 AJAX 라이브 검색을 만들고 싶지만 먼저 실행 방법을 배우는 데 도움이 필요합니다. (http://www.w3schools.com/php/php_ajax_livesearch.asp) 웹 사이트에있는 세 개의 코드 파일을 복사하고 html 파일은 모두 빈 폼 상자입니다. 어떻게 든 MySql과 연결해야합니까? 그렇다면 어떻게해야할까요?PHP 예제 AJAX 라이브 검색

index.html을 :

<html> 
<head> 
<script> 
function showResult(str) 
{ 
if (str.length==0) 
    { 
    document.getElementById("livesearch").innerHTML=""; 
    document.getElementById("livesearch").style.border="0px"; 
    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("livesearch").innerHTML=xmlhttp.responseText; 
    document.getElementById("livesearch").style.border="1px solid #A5ACB2"; 
    } 
    } 
xmlhttp.open("GET","livesearch.php?q="+str,true); 
xmlhttp.send(); 
} 
</script> 
</head> 
<body> 

<form> 
<input type="text" size="30" onkeyup="showResult(this.value)"> 
<div id="livesearch"></div> 
</form> 

</body> 
</html> 

livesearch.php :

<?php 
$xmlDoc=new DOMDocument(); 
$xmlDoc->load("links.xml"); 

$x=$xmlDoc->getElementsByTagName('link'); 

//get the q parameter from URL 
$q=$_GET["q"]; 

//lookup all links from the xml file if length of q>0 
if (strlen($q)>0) 
{ 
$hint=""; 
for($i=0; $i<($x->length); $i++) 
    { 
    $y=$x->item($i)->getElementsByTagName('title'); 
    $z=$x->item($i)->getElementsByTagName('url'); 
    if ($y->item(0)->nodeType==1) 
    { 
    //find a link matching the search text 
    if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) 
     { 
     if ($hint=="") 
     { 
     $hint="<a href='" . 
     $z->item(0)->childNodes->item(0)->nodeValue . 
     "' target='_blank'>" . 
     $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; 
     } 
     else 
     { 
     $hint=$hint . "<br /><a href='" . 
     $z->item(0)->childNodes->item(0)->nodeValue . 
     "' target='_blank'>" . 
     $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; 
     } 
     } 
    } 
    } 
} 

// Set output to "no suggestion" if no hint were found 
// or to the correct values 
if ($hint=="") 
    { 
    $response="no suggestion"; 
    } 
else 
    { 
    $response=$hint; 
    } 

//output the response 
echo $response; 
?> 

links.xml : 어떤 도움

<!-- Edited by XMLSpy® --><pages><link><title>HTML a tag</title><url>http://www.w3schools.com/tags/tag_a.asp</url></link><link><title>HTML br tag</title><url>http://www.w3schools.com/tags/tag_br.asp</url></link><link><title>CSS background Property</title><url>http://www.w3schools.com/cssref/css3_pr_background.asp</url></link><link><title>CSS border Property</title><url>http://www.w3schools.com/cssref/pr_border.asp</url></link><link><title>JavaScript Date Object</title><url>http://www.w3schools.com/jsref/jsref_obj_date.asp</url></link><link><title>JavaScript Array Object</title><url>http://www.w3schools.com/jsref/jsref_obj_array.asp</url></link></pages> 

덕분에

+0

선택하신 마스터 검색을보실 수 있습니다. 정말 대단합니다! – Si8

+0

이 파일을 웹 서버에 복사 했습니까? 이 예제에서는 데이터베이스 액세스가 필요하지 않습니다. 모든 관련 데이터는 .xml 파일에 있습니다. – sofl

+0

@ sofl 나는 이것을 텍스트 랭글러에 복사하고 문서 폴더의 폴더에 저장했습니다. 이것의 아무도는 웹 서버에서 i didnt는 내가 그것을 필요로 할 것이다라고 생각한다. 그러나 그것이 didnt 할 때 suprised했다. 그것들은 같은 폴더에있는 3 개의 개별 파일 들로서 붙여 넣기 방식과 동일합니다. @ SiKni8 당신은 링크를 배치 할 수 구글 그냥 전설 물건의 리그를 제공합니다 –

답변

1

내가 텍스트 언쟁이 점을 복사하여 문서 폴더의 폴더에 저장된 PHP 파일입니다. 이것의 아무도는 웹 서버에서 i didnt는 내가 그것을 필요로 할 것이다라고 생각한다. 그러나 그것이 didnt 할 때 suprised했다.

PHP 스크립트는 PHP 엔진이 설치된 웹 서버에서 실행됩니다. livescript.php를 올바르게 실행하려면 먼저 웹 서버 소프트웨어를 컴퓨터에 설치하거나 호스팅 제공 업체의 호스팅 공간을 임대하십시오.

웹 서버를 얻었 으면 웹 서버가 참조하는 디렉토리 (일반적으로 Unix 기반 서버의 경우 /home/<username>/public_html)에 파일을 설치하고 http://yourdomain.com/index.html을 통해 HTML 스크립트에 액세스하십시오.

+0

그래, 나는 이것이 문제가 될 것이라는 것을 깨달았다. 나는 아직 서버로 실험하고 싶지 않지만 public_html 폴더에 넣고 온라인으로 검색 상자를 찾자 마자. –

0

당신이 보인다 간단한 자바 스크립트를 사용하여 보내기 ajax 요청은 jQuery으로 훨씬 쉽습니다. 브라우저를 점검 할 필요가 없으며 다른 많은 것들이 jQuery에서 단순화되었습니다. 이제 흐름 부분입니다.

1.Anax 이벤트를 발생시키는 이벤트가 발생해야합니다. 그것은 흐리게, 초점, 클릭,로드, mouseout, mousein 같은 선택하실 수 있습니다. 코드는 다음과 같을 수 있습니다.

$($btn).click(function(){ 

insert your ajax request here 

}) 

이 버튼을

2.call 아약스

를 클릭 된 것을 말한다. PHP 파일의 데이터 3.process

$.ajax({ 

    url : "phpFile.php", 

    data : dataYouwantToSend, 

    success: function() { 

    code to do if the call is successful 
    } 

    }) 

당신이 에코 또는 PHP 파일의 인쇄 파일에서 응답으로 표시하는 것입니다 어떤 phpFile.php

인치

예를 에 대한 귀하의 PHP 파일은 단지 hello world이 될 것입니다 귀하의 아약스 요청에

echo "hello world"; 

응답을 포함합니다.

alert hello world

전체 코드는 다음과 같을 것이다 것입니다 예를 들어 위의 ajax success function

success : function (response){ //the variable in the function can be anything 
alert(response); 
} 

의 응답을 4.process. 이것은 html 파일입니다.

<input type="text" id="clickMe" /> 
<script src="ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script> 
$(function(){ 
$("#clickMe").click(function(){ 
$.ajax({ 
url : "phpFile.php", 
success : function(res) { 
alert(res); 
} 
}) 
}) 
}) 
</script> 

은 phpFile.php

echo "Hello world";