programing

jQuery를 사용하여 AJAX 응답에서 ID별 요소 찾기

oldcodes 2023. 11. 5. 14:58
반응형

jQuery를 사용하여 AJAX 응답에서 ID별 요소 찾기

php 페이지에 데이터를 올리고 나서 응답에 있는 특정 div의 텍스트를 받고 싶은데 올바르게 설정할 수 없는 것 같습니다.제가 jQuery를 잘하진 못하지만 보통은 금방 알아낼 수 있습니다.여기서 1분동안 내가 찾은 모든걸 시도해봤어요저는 단지 적절한 조합의 물건을 놓치고 있다고 생각합니다.

$.post("process.php", data , function (response) {  

       var w = window.open();    

       $(w.document.body).html(response); 

       console.log(typeof response); //  yeilds string 
       //create jquery object from the response html
       // var $data = $(response);   // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text


       var success =  $($.parseHTML(response)).find("#success"); 
       console.log('success'); 
       console.log(success);        // see screenshot
       console.log(success.text()); // yields nothing 
       console.log(success.val());  // yields undefined 
       // if (window.focus) {w.focus()}; 

 },'html');  

이것은 의 산출물입니다.console.log(success);빨간 상자는 내가 원하는 것이고...

![이 사진은 정말 작은 것 같습니다...제가 만들 때는 그렇게 작지 않았어요.여전히 읽을 수 있으면 좋겠습니다[1].

그리고 이렇게 할 수 있습니다.

var success =  $(response).find("#success"); 
console.log('success'); 
console.log(success);        // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text in red

응답은...

<html><head>
   <style>

      div.totals {
          font-family:calibri; font-size:.9em;  display:inline-block; 
          border-width: 2px;  border-style: solid; border-color: #FFD324; 
          background-color: #FAF5D7; color: #514721; 
          width: 500px; 
          }

      div.error_invalid {
         font-family:calibri; font-size:.9em;  display:inline-block; 
         border-width: 2px; border-style: solid; border-color: #9999CC; 
         background-color: #EEEEFF; color: #7979B8; 
     }

    </style>
    </head>
    <body>
    <div class="totals">Total new rows added: 0 out of 0<br/></div>
    <br/><br/>
    <div class="totals">Total updated rows: 0 out of 0 <br/></div>

    <div id="success">true</div>
    </body></html> 

그리고 나는 스타일 부분을 제거하려고 시도했고 그것이 도움이 되기를 바라며 html, 헤드, 바디 태그에 추가했습니다. 즉, 응답이 3개의 디브로만 구성된다면 동일한 문제가 발생합니다.

모든 요소가 동일한 수준에 있는 것을 주목하십시오.사용하셔야 합니다..filter()현재 선택 항목을 해당 선택 항목의 단일 요소로 좁히려면,.find()대신 현재 선택 항목의 하위 항목을 확인합니다.

var success =  $($.parseHTML(response)).filter("#success"); 
console.log(success); // div#success

ajax에서 전체 'html' 페이지를 반환받았지만, div로 래핑된 내용의 일부만 필요하고, 'html' 페이지 내에서 스크립트를 실행해야 합니다.

 $.ajax ({
  type: "POST",
  url : "contact.php",
  data: $("#formContactUs").serialize(),
  success: function(msg){
    console.log($(msg)); // this would returned as an array
    console.log(msg);    // return whole html page as string '<html><body>...</body></html>'
    $('#id').html($(content).closest('.target-class'));
    $('#id').append($(content).closest('script')[0]);  // append and execute first script found, when there is more than one script.
  }
});

@kevin 응답에서는 find ()가 하위 요소만 선택하고 첫 번째 요소는 선택하지 않기 때문에 예상대로 작동하지 않는 이유에 대해 힌트를 주었습니다.필터를 사용하는 것 외에도 현재 요소가 원하는 경우 $.close()도 작동합니다.음, 아마도 이 게시물은 @Kevin의 답변과 상당히 유사할 것입니다. 그것은 단지 다른 대안적인 답변을 제안하고 더 많은 세부사항을 제공하여 상황을 더 명확하게 만들기를 바랍니다.

위의 답변이 효과가 없다면 다음을 시도해 보십시오.

var successHtml = $($.parseHTML(response)).find("#success").html();

언급URL : https://stackoverflow.com/questions/16240436/finding-an-element-by-id-in-an-ajax-response-with-jquery

반응형