使用 jQuery 在 AJAX 响应中按 ID 查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16240436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:46:16  来源:igfitidea点击:

Finding an element by ID in an AJAX Response with jQuery

jqueryajaxselector

提问by gloomy.penguin

I need to post data to a php page and then I'd like to get the text of a certain div that is in the response but I can't seem to set things up correctly. I'm not too good with jQuery but I can usually figure things out fairly quickly... I've been at this for a minute and have tried everything I have found... I think I am just missing the right combination of stuff.

我需要将数据发布到 php 页面,然后我想获取响应中某个 div 的文本,但我似乎无法正确设置。我对 jQuery 不太擅长,但我通常可以很快地把事情弄清楚......我已经在这里待了一分钟,并尝试了我发现的一切......我想我只是错过了正确的组合.

$.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');  

this is the output of console.log(success);and the red box is what I want from the response...

这是输出,console.log(success);红色框是我想要的响应......

![this picture seems really tiny... it wasn't that tiny when I made it. I hope it is still readable][1]

![这张照片看起来真的很小……我做的时候还没有那么小。我希望它仍然可读][1]

and this does that:

这是这样做的:

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

Response is...

回应是...

<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> 

And I have tried removing the style part and I added in the html, head and body tags in hope that it would help.... meaning, I have the same issues if the response only consists of the three divs.

我已经尝试删除样式部分并添加了 html、head 和 body 标签,希望它会有所帮助....意思是,如果响应仅包含三个 div,我也会遇到同样的问题。

回答by Kevin B

Notice how all of the elements are on the same level? You need to use .filter()to narrow down the current selection to a single element in that selection, .find()will instead look at the descendants of the current selection.

注意所有元素如何在同一级别上?您需要使用.filter()将当前选择范围缩小到该选择中的单个元素,.find()而不是查看当前选择的后代。

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

回答by ken

I got a full 'html' page returned by ajax, but I only need partial of its content, which wrapped by a div and also I need to execute the script inside the 'html' page.

我得到了一个由 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 answer gave hints to why find() is not working as expected, as it only select its descendant but not the first element under consideration. Besides using filter, $.closest() also works if current element is what you are looking for. Well, probably this post quite similar to @Kevin's answer, it's just to suggest another alternative answer and gave more details which hopefully make thing clearer.

@kevin answer 暗示了为什么 find() 没有按预期工作,因为它只选择它的后代而不是考虑的第一个元素。除了使用过滤器,如果当前元素是您要查找的元素,$.closest() 也可以使用。好吧,可能这篇文章与@Kevin 的答案非常相似,只是建议另一个替代答案并提供更多细节,希望能让事情更清楚。