2013-04-09 4 views
0

Im Ajax에 조금 익숙하며, 어떤 부분이 잘못되었는지 알아 내려고 노력했습니다. 결과를 데이터베이스에서 가져 와서 xml에 던졌습니다. 메신저 XML을 통해 루핑하는 동안 xml 결과에서 ID 번호를 보내는 동안 PHP 파일을 실행하고 다음 PHP 파일에서 '반향'반환합니다. 메신저가 완전히 꺼져 있거나 한 부분이 누락되어 있는지 확실하지 않지만 결과가 '정의되지 않음'으로 돌아옵니다.아약스에서 php 데이터를 반환하려고 시도했습니다.

여기에 메아리를 표시하고 표시하려고하는 php 파일이 있습니다.

echo rating_bar($id); 

function rating_bar($id) { 

    //other code, but $static_rater is what gets echoed 

    $static_rater = ""; 
    $static_rater .= '<div id="ratingblock" class="ratingblock">'; 
    $static_rater .= '<div id="unit_long'.$id.'">'; 
    $static_rater .= '<ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">'; 
    $static_rater .= '<li class="current-rating" style="width:'.$rating_width.'px;"></li>'; 
    $static_rater .= '</ul>'; 
    $static_rater .= '<p class="static">Rating: <strong> '.$rating1.'</strong>/'.$units.' ('.$count.' '.$tense.' cast)</p>'; 
    $static_rater .= '</div>'; 
    $static_rater .= '</div>'; 

    //return join("\n", $static_rater); 
    echo $static_rater;exit; 
} 

그리고이 결과를 얻으려는 .js 코드입니다.

downloadUrl("phpsqlajax_genxml.php", function(data) { 
    var xml = data.responseXML; 
    var bounds = new google.maps.LatLngBounds(); 
    var markers = xml.documentElement.getElementsByTagName("marker"); 
    // alert("downloadUrl callback, length="+markers.length); 

    for (var i = 0; i < markers.length; i++) { 
     var id = markers[i].getAttribute("id"); 
     if (!id) id = "id "+i; 
     var name = markers[i].getAttribute("name"); 
     if (!name) name = "name "+i; 
     var address = markers[i].getAttribute("address"); 
     if (!address) address = "address"; 
     var citystate = markers[i].getAttribute("citystate"); 
     if (!citystate) citystate = "city, ST"; 
     var phone = markers[i].getAttribute("phone"); 
     if (!phone) phone = "phone number"; 
     var type = markers[i].getAttribute("type"); 
     var point = new google.maps.LatLng( 
      parseFloat(markers[i].getAttribute("lat")), 
      parseFloat(markers[i].getAttribute("lng"))); 
     bounds.extend(point); 
     var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone; //html inside InfoWindow 
     var url = "starrating/_drawrating.php?id=" + id + ""; 
     //var contentString = ajaxLoad(url, parseResults, true); 
     //var contentString = downloadUrl(url, "POST", "text=" + text, completed); 
     var contentString = AJAX('starrating/_drawrating.php','id='+id, 
      function(data) { 
       var htm = $("#ratingblock").html(data); 
       alert(htm); 
      } 
    ); 

     var description = "<br><br>description" + id + " <br><b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone; //html inside InfoWindow 
     var icon = customIcons[type] || {}; 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: point, 
      icon: icon.icon, 
      shadow: icon.shadow, 
      animation: google.maps.Animation.DROP 
     }); 
     bindInfoWindow(marker, map, infoBubble, html, description, contentString); 
    } 
}); 


function AJAX(url, data, callback) 
{ 
var xmlhttp; 
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) 
    { 
     callback(xmlhttp.responseText); 
    } 
} 
xmlhttp.open("POST",url,true); 
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
xmlhttp.send(data); 

}

편집 : 좋아, 그래서이 놀아 이상 내 코드를 업데이트 필자. 나는이 사용하여 불을 지르고를 실행할 때 지금은 게시물을 볼 수 있고 응답은 이것이다 :

<div id="ratingblock" class="ratingblock"><div id="unit_long10"><ul id="unit_ul10" class="unit-rating" style="width:150px;"><li class="current-rating" style="width:0px;"></li></ul><p class="static">Rating: <strong> 0.0</strong>/5 (0 votes cast)</p></div></div> 

을하지만 경고는 [개체 개체]라고하고 정보창은 [개체 개체] 말한다. 그래서 나는 그 호출을 알고 데이터를 반환하고, 필자는 위의 섹션을 infowindow 내에 올바르게 나타낼 수있는 모든 것을 검색하고 시도했습니다. 이견있는 사람?

편집 # 2

임 새로운 접근 방법을 시도해보십시오.

var contentString = $.ajax({ 
          type:"POST", 
          url: "starrating/_drawrating.php", 
          dataType: "html", 
          data:"id="+id, 
          success: function(data){ 
            var $response=$(data); 
            $response.find('ratingblock').html(); 
            console.log($response); 
           } 
         }); 

콘솔에 "Object [div # ratingblock.ratingblock]"이 표시되지만 결과는 여전히 [object Object]입니다. 어떤 아이디어가 누락 되었습니까?

+0

PHP에서 문자열을 단순히 문자열로 작성하는 대신 배열로 빌드하는 이유는 무엇입니까? –

답변

0

$static_rater은 연결 연산자를 사용할 수없는 배열입니다. 당신이 게시물 본문에 URL과 부분에서 데이터의 일부를 보내는

$static_rater[] = "\n".'<div class="ratingblock">'; 
$static_rater[] = '<div id="unit_long'.$id.'">'; 
$static_rater[] = '<ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">'; 
$static_rater[] = '<li class="current-rating" style="width:'.$rating_width.'px;">Currently '.$rating2.'/'.$units.'</li>'; 
$static_rater[] = '</ul>'; 
$static_rater[] = '<p class="static">'.$id.'. Rating: <strong> '.$rating1.'</strong>/'.$units.' ('.$count.' '.$tense.' cast)</p>'; 
$static_rater[] = '</div>'; 
$static_rater[] = '</div>'."\n\n"; 
+0

죄송합니다, 이해가 확실하지 않습니다. PHP 파일을 자체적으로 실행하면 정확하게 표시됩니다. 그래서 _drawrating.php? id = 9를 실행하면 다시 돌아옵니다. – user1221768

0

는 게시물 본문에 두 부분을 넣어. 즉

AJAX('starrating/_drawrating.php','id='+id, 
+0

나는 이것을 시험해 보았고 여전히 정의되지 않은 것으로 되돌아왔다. 아마도 함수에서 뭔가 빠졌습니다 (결과) {? – user1221768

+0

@ user1221768 그냥'callback (xmlhttp.responseText);'를 호출하지 않고'$ _POST [ 'id']'를 통해 id를 가져옵니다. – Musa

1

AJAX의 A는 JS가 PHP 데이터가 다시 표시 될 때까지 기다리지 않는다는 의미 인 비동기를 나타냅니다. 따라서 AJAX 호출의 결과를 변수에 할당 할 수 없기 때문에 일부 데이터가 다시 호출되면 호출 할 함수를 등록해야합니다. 현재 비어있는 function(result) {} 콜백이 대상입니다.

누군가에게 뭔가를 가져오고 돌아올 때까지 그 자리에 얼지 않고 오히려 그 자리에서 계속하는 것과 같습니다. 콜백 함수는이 약간 유추 한 비유에서, 그들이 돌아올 때 무엇을 하려는지에 대한 메모입니다.

관련 문제