-2

我尝试使用 jquery 更新列表,但由于某种原因,POST 函数返回奇怪的对象。任何想法如何从 POST 答案中检索数据?

 var ans = jQuery.post("mysite.com", {name: "John"})
 var cont = jQuery( ans ).find( "#content" );
 alert(cont);

和页面:

<?php
   echo "<div id='content'>";
   echo $_POST['name'];
   echo '</div>';
?>

当我尝试使用以下命令读取对象的所有字段时,它会提醒 [对象]:

answ = '';
for( var key in ans ) {
   answ = answ + 'key: ' + key + '\n' + 'value: ' + ans[key];
}
jQuery('#somediv').html( answ );

任何想法如何获得我在另一页上的回应?

编辑:我按照你们的建议尝试了以下操作:

var ans = jQuery.post("mysite.com", {name: "John"});
jQuery.when(ans).then(function(answ){
var cont = jQuery( answ ).find( "#content" );
alert(cont);
});

并且:

var ans = jQuery.post("mysite.com", {name: "John"}, function(answ){
var cont = jQuery( answ ).find( "#content" ).html(); 
alert(cont);
});

但它仍然不起作用。警报根本没有显示这意味着它之前有问题。

4

3 回答 3

1

jQuery.post返回一个延迟的,而不是请求的结果,因为这是一个异步函数,并且脚本在处理请求时继续。

post的典型用法之一是传递一个回调,该回调将在请求完成时调用:

 jQuery.post("mysite.com", {name: "John"}, function(ans){
    var cont = jQuery( ans ).find( "#content" );
    // use cont
 });

但是,由于您的 URL 是“mysite.com”,您可能还会遇到同源策略问题。要解决此问题,您必须在服务器上设置相关的 CORS 标头

于 2013-10-15T06:51:07.403 回答
0

而不是下面的代码:

var cont = jQuery( ans ).find( "#content" );

使用以下代码:

var cont = jQuery( ans ).find( "#content" ).html(); 
 //to get the content use the .html() or .text()
于 2013-10-15T06:53:29.597 回答
0

@dystroy 是对的。你也可以使用延迟:

var defer = jQuery.post("mysite.com", {name: "John"});
$.when(defer).then(function(ans){
    var cont = jQuery( ans ).find( "#content" );
    // use cont
});
于 2013-10-15T06:53:49.090 回答