ajax 처리 질문 부탁드립니다ㅠㅠㅠ급해요
본문
$(".address_btn").click(function() {
let value = this.value;
ajax_url = "<?php echo G5_URL?>/petroom/ajax_petroom_list.php";
$('#address_searching').val(value);
let frmData = $("#search_wrap").serialize();
console.log(frmData);
$.ajax({
type: "POST",
url: ajax_url,
data: frmData,
dataType: "JSON",
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
우선 폼안에있는 값들은 전송이 됩니다.
ajax.php
<?php
include_once $_SERVER["DOCUMENT_ROOT"]."/common.php";
$find_machine = trim( $_REQUEST['search_machine'] );
$find_address = trim( $_REQUEST['address_searching'] );
$lat = $_REQUEST['lat'] ? $_REQUEST['lat'] : 33.450701 ;
$lon = $_REQUEST['lon'] ? $_REQUEST['lon'] : 126.570667 ;
// alert($find_address);
// if( $find_address ) {
$address = array( '전체','서울','경기','인천','대전','대구','부산','광주','울산','세종','강원','충북','충남','전북','전남','경북','경남','제주' );
$address_2 = array( '','서울시','경기도','인천시','대전시','대구시','부산시','광주시','울산시','세종시','강원도','충청북도','충청남도','전라북도','전라남도','경상북도','경상남도','제주도' );
$address_3 = array( '','서울특별시','','인천광역시','대전광역시','대구광역시','부산광역시','광주광역시','울산광역시','세종특별자치시','강원특별자치도','','','','','','','제주특별자치도');//도시찾기 버튼으로 검색시
if($find_address == "전체"){
$sql = "select *
from sw_machine_holder
where mapLatitude > '' and
mapLongitude > '' and
petroom = 'Y'
GROUP BY petroom_name
";
$row = "SELECT count(count) as total
FROM (SELECT count(petroom_name) as count FROM sw_machine_holder
WHERE petroom = 'Y'
and mapLatitude > '' and
mapLongitude > '' GROUP BY petroom_name)
as count";
$status = "select * from sw_machine_holder where petroom = 'Y' and admin_status = '이용가능'";
}else {
$j = array_search( $find_address, $address ) === false ? ( array_search( $find_address, $address_2 ) === false ? array_search( $find_address, $address_3 ) : array_search( $find_address, $address_2 ) ) : array_search( $find_address, $address );
if ( $j !== false ) {
$fine_address_like = " and ( ";
if ( $address[$j] > '' ) {
$fine_address_like .= "machine_address like '" . $address[$j] . "%'";
" or machine_address like '" . $address_2[$j] . "%' or machine_address like '" . $address_3[$j] . "%' )";
}
if ( $address_2[$j] > '' ) {
if ( $fine_address_like != "( " ) {
$fine_address_like .= " or ";
}
$fine_address_like .= "machine_address like '" . $address_2[$j] . "%'";
}
if ( $address_3[$j] > '' ) {
if ( $fine_address_like != "( " ) {
$fine_address_like .= " or ";
}
$fine_address_like .= "machine_address like '" . $address_3[$j] . "%'";
}
if ( $fine_address_like != "( " ) {
$fine_address_like .= " ) ";
}
}
$sql = "select petroom_name, mapLatitude, mapLongitude
from sw_machine_holder
where
mapLatitude > '' and
mapLongitude > '' and
petroom = 'Y'
$fine_address_like
GROUP BY petroom_name, mapLatitude, mapLongitude
";
$row = "SELECT count(count) as total
FROM (SELECT count(petroom_name) as count FROM sw_machine_holder
WHERE petroom = 'Y' and machine_address like '$find_address%' GROUP BY petroom_name)
as count";
}
//}
// echo $sql;
$query = sql_query( $sql );
$machine_count = sql_query($row);
$mapNameArray = array();
$statusArray = array();
$latArray = array();
$lotArray = array();
$arr = array();
$arr["data"] = array();
for($i=0; $row=sql_fetch_array($query); $i++){
$find_status_sql = sql_fetch("select * from sw_machine_data where petroom = 'Y' and data2 = '{$row['machine_uuid']}' order by idx desc limit 1");
$find_status = $find_status_sql['data1'];
$make_status = explode(' ', $find_status);
$mapNameArray[$i] = $row['petroom_name'];
$latArray[$i] = $row['mapLatitude'];
$lotArray[$i] = $row['mapLongitude'];
$status_check = sql_fetch("select petroom_name from sw_machine_holder where petroom = 'Y' and admin_status != '사용불가능' and petroom_name ='$mapNameArray[$i]'");
if($status_check['petroom_name'] == $mapNameArray[$i]){
$statusArray[$i] = "이용가능";
$row['admin_status'] = "이용가능";
} else {
$statusArray[$i] = "이용불가";
$row['admin_status'] = "이용불가";
}
}
// array_push( $arr["data"], $row);
array_push( $arr["data"], $mapNameArray);
array_push( $arr["data"], $latArray);
array_push( $arr["data"], $lotArray);
array_push( $arr["data"], $statusArray);
//var_dump( $arr );
// echo json_decode( $arr );
//$data = json_decode( $arr );
echo json_encode( $arr );
?>
대충 폼안에 주소 value가 들어가서 그 값을 찾아 배열로 보내주는 설계입니다.
<h4>
<?php echo $mapNameArray[$i] ;?>
<!-- 지점명 -->
</h4>
<p>
<?php echo $row['machine_address'] . ( ( $row['mapDetail'] ) ? "<br />" . $row['mapDetail'] : "" ) ?>
<!-- 전화번호 -->
</p>
<!-- 이용상태 -->
<?php
if($status_check['petroom_name'] == $mapNameArray[$i]){
?>
<span>이용가능</span>
<?php
} else { ?>
<span class="not">이용불가</span>
<?php
}
?>
그리고 form.submit으로 실행시켰을때 표시되는 코드입니다. 하지만 form.submit으로 하게 되면 reload가 되어 ajax로 실행하고싶은건데 배열은 찍히는데 json 완전초보라 배열을 표시할줄을 모릅니다ㅠㅠ 아니면 그냥 ajax에서 배열로 내보내지 않고 비동기로 위에 form.submit으로 뿌려주는 방법이 있을까요?? 제발알려주세요ㅠ
!-->!-->!-->답변 1
$.ajax({
type: "POST",
url: ajax_url,
data: frmData,
dataType: "html",
success: function(response) {
$("#toshowhtml").html(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
dataType: "html", 이와 같이 변경하시고
$("#toshowhtml").html(response);
보여질 <div id="toshowhtml">.....
이렇게 ajax 요청하고
ajax.php 에서
// echo json_encode( $arr );
위의 부분을 삭제하고
보여질 html 내용을 for 으로 구성하거나 해서 만들어주면 그대로 가져 올 것입니다.
ajax.php 에서 content type 을 html로 해주면 될 것입니다.
header("Content-type: application/xml; charset=utf-8"); 이렇게 맨위에 선언해 주세요
이렇게 하면 원하는 형태로 데이타를 가져울 수 있을 것입니다.