在jQuery中提取Ajax返回数据

在jQuery中提取Ajax返回数据,jquery,ajax,callback,Jquery,Ajax,Callback,我已经完成了jQuery和Ajax,但是我无法将响应放入Div元素中。代码如下: Index.html $.ajax({ type:"POST", url: "ajax.php", data:"id="+id , success: function(html){ $("#response").html(data); } }); 它正在接收对我的的响应 ajax.php将以下代码返回到index.html文件: <div id ="o

我已经完成了jQuery和Ajax,但是我无法将响应放入Div元素中。代码如下:

Index.html

$.ajax({
    type:"POST",
    url: "ajax.php",
    data:"id="+id ,
    success: function(html){
        $("#response").html(data);
    }
});
它正在接收对我的
的响应

ajax.php
将以下代码返回到
index.html
文件:

<div id ="one"> OneVal </div>
<div id ="sub"> SubVal </div>
OneVal
SubVal

我是否能够将OneVal和Subval提取到变量中,以及如何提取“OneVal”和“Subval”,而不是上述响应?

您可以对根据响应创建的jQuery对象使用
.filter

success: function(data){
    //Create jQuery object from the response HTML.
    var $response=$(data);

    //Query the jQuery object for the values
    var oneval = $response.filter('#one').text();
    var subval = $response.filter('#sub').text();
}

.find
更改为
.filter
..

我注意到您的success函数具有参数“html”,并且您正在尝试将“数据”添加到元素
html()。。。将其更改为两个匹配:

$.ajax({
    type:"POST",
    url: "ajax.php",
    data:"id="+id ,
    success: function(data){
        $("#response").html(data);
    }
});

您可以像下面的示例一样使用
json

代码:

$array
是数组数据,jQuery代码是:

$.get("period/education/ajaxschoollist.php?schoolid="+schoolid, function(responseTxt, statusTxt, xhr){
    var a = JSON.parse(responseTxt);
    $("#hideschoolid").val(a.schoolid);
    $("#section_id").val(a.section_id);
    $("#schoolname").val(a.schoolname);
    $("#country_id").val(a.country_id);
    $("#state_id").val(a.state_id);
}

您还可以使用jQuery上下文参数

选择器上下文

默认情况下,选择器在DOM中执行搜索 在文档根目录下。但是,可以为其提供另一个上下文 使用$()函数的可选第二个参数进行搜索

因此,您还可以:

success: function(data){
    var oneval = $('#one',data).text();
    var subval = $('#sub',data).text();
}

var plz=$response.find('#title').text();警报(plz);它抛出空值,如果我需要做任何其他事情来获得值,在我看到你的后续文章之前,花30分钟玩这个。编辑为包含筛选器:d您能解释一下为什么不能在此处使用.find()吗?我已经对它进行了测试,并且确实在使用.filter()时得到了结果,但在使用.find()时没有得到结果。…@Yves Van Broekhoven,因为没有包装根元素,所以jquery对象包含多个根节点,您必须过滤它们谢谢!!我是jQuery的新手,但我需要var$response(data.d)才能让它工作。为我添加了.df,我调整了上面的使用.html()而不是.text()b/c,我需要检索完整的html,而不仅仅是一个文本字符串。i、 e.
var-oneval=$response.filter('#one').html()如果(data.d){data=data.d}那么结尾“}”怎么办?你能再解释一下放在哪里以及它的作用吗?否则,你可能很难理解你在这里想要表达什么。
success: function(data){
    var oneval = $('#one',data).text();
    var subval = $('#sub',data).text();
}
on success: function (response) { alert(response.d); }