복붙노트

jQuery를 사용하여 AJAX 요청 콜백

PHP

jQuery를 사용하여 AJAX 요청 콜백

나는 AJAX를 다루기 위해 jQuery를 처음 사용하고 기초를 배우기위한 기본 스크립트를 작성했다. 현재 동일한 파일에 AJAX 요청을 게시 중이며 해당 AJAX 호출의 결과를 기반으로 일부 추가 처리를 수행하려고합니다.

여기 내 코드가 있습니다 :

**/*convertNum.php*/**

$num = $_POST['json'];
if (isset($num))
 echo $num['number'] * 2;
?>

<!DOCTYPE html>
<html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <style type="text/css">
 td {border:none;}

 </style>
 </head>
 <body>

 <table width="800" border="1">
 <tr>
 <td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
 <td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
 </tr>

 <tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
 </table>



 <script>
 $(document).ready(function () {
 $('#getNum').click(function () {
 var $numSent = $('#numSend').val();
 var json = {"number":$numSent};

 $.post("convertNum.php", {"json": json}).done(function (data) 
 {
 alert(data);
 }
 );

 });
 });
 </script>
 </body>
</html>

내가 '2'라는 숫자를 제출하면 나는 응답을 얻습니다.

4

<!DOCTYPE html>

<html>

<head>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

 <style type="text/css">

td {border:none;}

</style>

</head>

<body>



<table width="800" border="1">

 <tr>

 <td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>

 <td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>

 </tr>

 <tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>

</table>

<script>

$(document).ready(function () {

 $('#getNum').click(function () {

 var $numSent = $('#numSend').val();

 var json = {"number":$numSent};

 $.post("convertNum.php", {"json": json}).done(function (data) 

 {

 alert(data);

 }

 );



 });

});

</script>
</body>
</html>

분명히 나는 ​​단지 '4'라는 숫자를 받아들이고 사용하는 것에 관심이있다. 따라서 내 질문에 : 내가 원하는 데이터를 정확하게 지정하는 가장 좋은 방법은 무엇인가?

내가 가진 몇 가지 생각 :

이 일을하는 우아한 방법이있을 것이라고 확신합니다. 어떤 제안을 주셔서 감사합니다!

해결법

  1. ==============================

    1.

    우아한 방법은 별도의 (!) PHP 파일로 현재 PHP의 2 배 부분 만 출력하는 것입니다. 그런 다음 현재 PHP에서 새로운 PHP로 AJAX 요청을 생성합니다.

  2. ==============================

    2.

    나는이 게시물이 당신이보고있는 것의 한 측면, 즉 경고 상자에 전체 페이지의 반향에 대답한다고 믿습니다.

    다음은 AJAX의 기초를 익히는 데 유용한 게시물입니다.

    간단한 예

    보다 복잡한 예제

    드롭 다운 1의 선택에 따라 드롭 다운 2 채우기

  3. ==============================

    3.

    die ()를 추가 할 수 있습니다. 같은 페이지에 계속 머물고 싶다면 숫자를 반향 한 후 그러면 스크립트 실행이 종료됩니다. if 문에 대괄호를 추가하는 것을 잊지 마십시오.

    if (isset($num)) {
      echo $num['number'] * 2;
      die();
    }
    

    그러나 가장 우아한 솔루션은 아닙니다.

  4. ==============================

    4.

    NOTE * 더 나은 접근법은 이와 같은 것을 별도의 파일에 보관하는 것이고, 특히 네이밍 변환을 잘 사용하면 읽기 쉽고 이해하기 쉽습니다.

    그것은 나쁜 절차 접근이지만 여기에 내가 간다 :) :

    <?php
    $num = $_POST['json'];
    if (isset($num))
     echo ($num['number'] * 2);
     die();
    ?>
    

    또는 더 나은 아직 :

    <?php
    $num = $_POST['json'];
    if (isset($num))
     die($num['number'] * 2); //In case of error you could put them in brackets
    ?>
    

    추신

  5. ==============================

    5.

    나는 이것이 얼마나 효율적인지 모르지만 다음과 같이 할 수 있습니다 :

    <?php
     /*convertNum.php*/
     $num = isset($_POST['json']) ? $_POST['json'] : NULL; //you have errors in this line
     if (!is_null($num)){
      echo $num['number'] * 2;
      exit(); //exit from script
     }
    ?>
    
  6. from https://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery by cc-by-sa and MIT lisence