programing

Symfony 및 Jquery로 POST Ajax 요청하는 방법

stoneblock 2023. 10. 6. 20:51

Symfony 및 Jquery로 POST Ajax 요청하는 방법

나는 내 심포니 프로젝트에 지도 매개 변수를 저장해야 합니다. 이를 위해서는 컨트롤러에 정보를 전달할 수 있는 일부 Ajax를 내 보기에 구현해야 합니다.

문서를 읽었는데 코드를 좀 써봐도 안 되네요.그리고 Ajax는 디버그에 정말 고통스럽습니다.컨트롤러 부분은 다음과 같습니다.

 /**                                                                                   
 * @Route("/ajax", name="_recherche_ajax")
 */
public function ajaxAction()    
{
    $isAjax = $this->get('Request')->isXMLHttpRequest();
    if ($isAjax) {         
        return new Response('This is ajax response');
    }
    return new Response('This is not ajax!', 400);
}

그리고 JS:

map.on('zoomend', function(e) {
    // use callback e variable
    console.log('zoom: ' + e.target.getZoom());

    $.ajax({
        type: "POST",
        url: "/recherche/ajax",
        data: {
           zoom: e.target.getZoom()
        },
        dataType: "json",
        success: function(response) {
            console.log(response);
        }
    });

});

url을 확인합니다.recherche/ajax실제로 존재하며 예상대로 'This is not Ajax'를 반환합니다.하지만 console.log는 어떤 값도 반환하지 않습니다...

그게 옳은 방법입니까?

편집 : POST Request를 컨트롤러에서 처리할 수 없는 것 같습니다.주석을 다음과 같이 수정하려고 했습니다.

 /**                                                                                   
 * @Route("/ajax", name="_recherche_ajax")
 * @Method({"GET", "POST"})
 */

하지만 다음과 같이 돌아옵니다.

([Semantical Error] The annotation "@Method" in method MySite\SiteBundle\Controller\RechercheController::ajaxAction() was never imported. Did you maybe forget to add a "use" statement for this annotation?) 

이거 먹어봐요.

/**                                                                                   
 * @Route("/ajax", name="_recherche_ajax")
 */
public function ajaxAction(Request $request)    
{
    if ($request->isXMLHttpRequest()) {         
        return new JsonResponse(array('data' => 'this is a json response'));
    }

    return new Response('This is not ajax!', 400);
}

Ajax request를 보내실 경우 반환해야 합니다.json/plaintext/xml전체가 아닌 데이터Response물건.

추신: 다음에 대한 사용 설명을 추가하는 것을 잊지 마십시오.Request그리고.JsonResponse

EDIT : 추가한 오류 메시지에서 알 수 있듯이 주석을 가져와야 합니다.@Method다음을 사용하여:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

저는 인터넷 전체를 살펴보았지만 비슷한 문제에 대한 해결책을 찾지 못했습니다.근데 발견했어요-> 저는 컨트롤러 문제도 javascript/jquery/ajax 문제도 보안 문제도 없었습니다.그것은... ...기다려요...HTML로. type="button"을 HTML 태그에 추가해야 했고, 그렇지 않으면 전체 페이지가 새로워졌습니다.디버깅 목적으로 4시간을 낭비했습니다.교훈을 얻었소

문제 디버그 방법은? 1. ajax가 클라이언트 측에서 포스트를 보내고 포스트 경로를 일치시키는지 확인합니다.파이어폭스 -> f12 -> 네트워크 -> POST 이벤트 보기 2.-> /app_dev.php/ (dev environment) -> Get Request/Response 하위 메뉴 end take last 10에서 symphony profiler(매우 유용한 도구!)를 확인합니다. POST 경로를 자세히 보면 반환 코드와 매개 변수가 있는지 확인합니다. (HTML 응답 이외의 설정이 있으면 응답이 나타나지 않습니다.) 3.컨트롤러에서 이 경로 내의 스크립트가 실행되었는지 확인할 수 있는 몇 가지 작업을 수행합니다.그렇다면 서버 측(컨트롤러) 또는 클라이언트 측(twig/ajax/html) 4에서 응답이 없습니다.코드 예제:

html의 버튼 (이것은 나의 문제였습니다)

<button name="button" id="button" class="button" type="button" value="100"> Click me </button> 

html 또는 포함된 다른 js 파일의 Ajax:

function aButtonPressed(){
        $.post('{{path('app_tags_sendresponse')}}',
            {data1: 'mydata1', data2:'mydata2'},
            function(response){
                if(response.code === 200 && response.success){
                    alert('success!');
                }
                else{
                    alert('something broken');
                }
            }, "json");
    }

이제.. 서버 쪽입니다.컨트롤러:

namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class JsonApiController extends Controller
    /**
         * @Route("/api/programmers")
         * @Method("POST")
         */
        public function sendResponse()
        {
            if(isset($_POST['data1'])){
                $json = json_encode(array('data' => $_POST['data1']), JSON_UNESCAPED_UNICODE);
                file_put_contents("test.json", $json);
                return new JsonResponse($json);
            }
            return new Response('didn't set the data1 var.');
        }
    }

File put contents웹 디렉토리에 새 파일을 만듭니다.합니다를 얻지

언급URL : https://stackoverflow.com/questions/19375349/how-to-make-a-post-ajax-request-with-symfony-and-jquery