在jQuery中提取Ajax返回数据
我已经完成了jQuery和Ajax,但我无法将响应转换为Div元素。 这是代码:
的index.html
$.ajax({ type:"POST", url: "ajax.php", data:"id="+id , success: function(html){ $("#response").html(data); } });  它正在接收我对<div id="response"></div> 。 
  ajax.php将以下代码返回到index.html文件中: 
 <div id ="one"> OneVal </div> <div id ="sub"> SubVal </div> 
我能否将OneVal和Subval提取到一个variables中,以及如何提取“OneVal”和“SubVal”,而不是上面的响应?
 你可以在从响应中创build的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 … 
 我已经注意到,你的成功函数有参数“HTML”,你试图添加“数据”元素的html() …改变它,所以这两个匹配: 
 $.ajax({ type:"POST", url: "ajax.php", data:"id="+id , success: function(data){ $("#response").html(data); } }); 
 你可以像下面的例子一样使用json 。 
PHP代码:
 echo json_encode($array); 
  $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 上下文参数。 链接到文档
select器上下文
默认情况下,select器从文档根开始在DOM内执行search。 但是,通过使用$()函数的可选第二个参数,可以为search提供备用上下文
所以你也可以有:
 success: function(data){ var oneval = $('#one',data).text(); var subval = $('#sub',data).text(); } 
function(响应){alert(response.d); }