简体   繁体   English

$ .post返回[object Object]

[英]$.post returns [object Object]

Why this returns [object Object] ??? 为什么返回[object Object] ??? I want to return #new content in to a alert. 我想将#new内容返回到警报中。 (actually i want to append that text to a new div, I can do that if this [object Object] problem resolved) (实际上,我想将该文本附加到新的div上,如果此[object Object]问题解决了,则可以这样做)

<script type="text/javascript">
      $(document).ready(function() {
        $.post("post.php", {"test": "hello"}, function(data) {
           var myDiv = $(data).filter("#new");
           alert(myDiv);
        });
      });
</script>

It works perfectly fine. 它工作得很好。

alert does not show all the properties of an object, which is what you are trying to alert. alert 显示的对象,这是你正在试图提醒的所有属性。
Try using the console for that: 尝试为此使用console

//info on the jQuery DOM obj:
console.log(myDiv);

//info on the jQuery obj:
console.dir(myDiv);

For example: http://jsfiddle.net/agNNW/ (Thanks @Esailija ) 例如: http : //jsfiddle.net/agNNW/ (感谢@Esailija

Because myDiv is object you have to access html in it, 由于myDiv是对象,因此您必须访问其中的html,

use html() function of jquery if you want html, use text() function of jquery if you want text instead of html 如果要使用html,请使用jquery的html()函数;如果要使用文本而不是html,请使用jquery的text()函数

 myDiv.html();

   $(document).ready(function() {
    $.post("post.php", {"test": "hello"}, function(data) {
       var myDiv = $(data).filter("#new");
       alert(myDiv.html());
    });
  });

I'm going to take a wild guess and say it is working perfectly. 我将做出一个疯狂的猜测,并说它运行良好。 If your myDiv is a DOM element, that is an object and alert has no idea how to print it. 如果myDiv是DOM元素,则该对象是一个对象, alert不知道如何打印它。 Never rely on alert for debugging purposes. 切勿将警报用于调试目的。 Try appending it to a DOM element and it will probably work fine. 尝试将其附加到DOM元素上,它可能会正常工作。

Like many jQuery methods, .filter() returns a jQuery object, so your current alert is quite correctly showing [object Object] . 像许多jQuery方法一样, .filter()返回一个jQuery对象,因此您当前的警报显示[object Object]相当正确。

Assuming data is a string of html, you can see the contents of the #new element within that html by doing this: 假设data是一个html字符串,您可以通过执行以下操作来查看该html中的#new元素的内容:

var myDiv = $(data).filter("#new");
alert(myDiv.html());
// or
alert(myDiv.text());
// or put the text in a variable:
var newText = myDiv.html();
// or
var newText = $(data).filter("#new").html();

To append to your other element: 附加到其他元素:

$("#someotherelement").append(myDiv.html());

myDiv will contain a jQuery object, so if you want to see its' contents, you shoud use myDiv将包含一个jQuery对象,因此,如果要查看其内容,则应使用

alert(myDiv.text());

or 要么

alert(myDiv.html());

or 要么

console.log(myDiv);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM