微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我需要将数据发布到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');

这是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,head和body标签,希望它会有帮助….意思是,如果响应只包含三个div,我有同样的问题。

注意所有元素是否在同一级别?您需要使用.filter()将当前选择缩小到该选择中的单个元素.find()将查看当前选择的后代。
var success =  $($.parseHTML(response)).filter("#success"); 
console.log(success); // div#success

原文地址:https://www.jb51.cc/ajax/160312.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐