개발! 딱 깔끔하고 센스있게!

AJAX 호출 중에 PHP 에서 JSON 상대로 돌아갈까요? 본문

개발 스크랩 메모/PHP

AJAX 호출 중에 PHP 에서 JSON 상대로 돌아갈까요?

렉사이 2020. 12. 14. 23:55

다음은 jQuery AJAX 호출 기간에 호출된 PHP 코드:

mysqli->stmt_init(); $stmt = $conn->mysqli->prepare($query); $stmt->bind_param('s', $_POST['ID']); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); echo json_encode($row); ?> 

클라이언트 코드:

$.post(url, {ID:$('#ddlClients').val()}, function(Result){ // Result } ); 

AJAX 호출이 성공했습니다.

나는 결과의 가치를 얻었다

": {" 주소 1 ":" 분구 사무실 1 "," 주소 2 ":" XYZ 로 ",...등등

내가 원하는 것은 Result.Address 1, Result.Address 2 등이다.

하지만 나는 위쪽 코드를 사용할 수 없다.

나는 $row=$result - > fetch u object () 와 $row=$result > fetch array () 를 사용해 보았지만 사용할 수 없습니다.

서버 엔드 코드를 통해 이루어질 수 있다는 것을 알고 있습니다:

$row = $result->fetch_assoc(); $retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......); echo json_encode($retVal); 

혹은

$row = $result->fetch_object(); $retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......); echo json_encode($retVal); 

클라이언트 자바스크립트와 JSON 대상으로 직접 보낼 수 있는 방법이 하나 없다.

우선 수동적으로 수동적으로 수동적으로 배열할 필요는 없다.

대답

PHP 스크립트에서 얻은 호응은 순수 텍스트이다.

하지만 회향 함수에서 $.parseJSON 을 사용하여 이 문자열을 상대로 분석할 수 있습니다:

$.ajax({ url : url,//note that this is setting the `url` property to the value of the `url` variable data : {ID:$('#ddlClients').val()}, type : 'post', success : function(Result){ var myObj = $.parseJSON(Result); //you can now access data like this: //myObj.Address_1 } } ); 

AJAX 에서 호출된 dataType 속성을 json 으로 설정하여 jQuerry를 실행할 수 있습니다:

$.ajax({ url : url//note that this is setting the `url` property to the value of the `url` variable data : {ID:$('#ddlClients').val()}, dataType : 'json', type : 'post', success : function(Result){ //you can now access data like this: //Result.Address_1 } } ); 

이상의 예제 옵션 서버의 응답은 다음의 형식을 적용합니다 (질문에서):

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"} 
Comments