JQuery:什么是通过ajax将html注入DOM的最简单的方法?


JQuery: what's the simplest way to inject html via ajax into the DOM?

我正在构建一个交互式表单,并根据用户给出的答案通过ajax注入新的问题。

我的问题是它看起来像注入的html是不可见的JQuery。

可以看到http://atpc.info/f/pesquisa1.htm在注入的HTML中,click函数不起作用。

//pesquisa1.js
$('a.continuar_r').live('click',function(event) {
    var id_p=$('input:radio:first').attr('name');
    var v_r=$('input:radio:checked').val();
    alert(v_r);
    if (!v_r) $('#update_p').hide().text('Ops! Selecione uma opção').fadeIn('slow');
    else {
        $('#update_p').hide();
        var fieldset=$(this).closest('fieldset');
        fieldset.hide();
        fieldset.nextAll('fieldset:first').fadeIn('slow');
        $.post(
            'pesquisa1.php',
            { id_p:id_p, v_r:v_r },
            function(data){
                //alert('Retorno:'n' + data);
                $('#status_p').hide();
                $('form').append($(data).hide().fadeIn('slow'));
                $('label').css('display','block');
            }
        );
    }
});

顺便说一下,"id_p"是问题的id, "v_r"是答案的值(选择选项或书面答案)。

现在HTML:

//pesquisa1.htm
<form id="form_p" action="">
    <input type="hidden" id="origem_p" value="">
    <input type="hidden" id="proposito_p" value="">
    <fieldset class="p_satisfeito">
        <legend>Você está satisfeito com os seus resultados atuais?</legend>
        <label for="for_s"><input type="radio" id="for_s" name="p_satisfeito" value="s">Sim</label>
        <label for="for_n"><input type="radio" id="for_n" name="p_satisfeito" value="n">Não</label>
        <a class="continuar_r">Continuar &rarr;</a>
    </fieldset>
    <small id="update_p"></small> <span id="status_p"></span>
</form>

我在这里展示一个非常简化的PHP代码版本,它是一个交互式表单。

//pesquisa1.php
<?
echo<<<FORM
<label for="for_y1"><input type="radio" id="for_y1" name="p_satisfeito1" value="ohy">Oh, Yes!</label>
<label for="for_n1"><input type="radio" id="for_n1" name="p_satisfeito1" value="ohn">Oh, No!</label>
<a class="continue_r">Continue &rarr;</a>
FORM;
?>

看起来我不能使用已经加载的javascript与刚刚加载的新html进行交互…

编辑:

如果我在我的php中插入一些javascript,魔法会回来,但我仍然无法访问在第一个页面加载中声明的变量。

//form.php//
<?
echo<<<FORM
<label for="for_y1"><input type="radio" id="for_y1" name="p_satisfeito1" value="ohy">Oh, Yes!</label>
<label for="for_n1"><input type="radio" id="for_n1" name="p_satisfeito1" value="ohn">Oh, No!</label>
<a class="continue_r">Continue &rarr;</a>
<script>
    $('a.continue_r').click(function(event) {
        alert('Hi!');
        var id_p=$('input:radio:first').attr("name")
        alert('id_p');
    });
</script>
FORM;
?>

谢谢!

您没有在任何地方注入从POST请求返回的数据,因此没有人知道它。你可以这样做:

$.post('form.php', {params...}, function(html) {
  $('body').append(html);
  // Now it's in the DOM, you can access it.
}, "text");

我认为这是替换和范围的问题。您正在用返回的内容替换#stage的html,然后尝试通过DOM获取id_p,但您刚刚替换了该内容。另外,我猜您最初打算使用id_p和v_r,因为它们被声明但从未使用过。因为这些变量是在post函数中声明的,所以当您稍后需要它们时,它们将不可用。你需要在更高的作用域中声明它们。

最后我注意到,在form.php中,你试图获得一个元素的名称,但你在同一个文件中设置元素。你真的需要名字吗?

还有一点。我猜您正在尝试收集对一系列问题的响应,这些问题通过ajax单独加载,对吗?…如果你有两个以上的问题,那么考虑把答案放在一个数组中。

试试这个:新html:

<script type="text/JavaScript"> 
  var responses = [];
  $(document).ready
  (
    function()
    {
      loadPergunta();
      $("a.continuar").click
      (
        function()
        {
          var response  = $("#pergunta input:checked").val();
          if(typeof(response)=="undefined") response = $("#pergunta input").val();
          alert(response);
          responses[responses.length] = response;
          loadPergunta(responses.length+1);
        }
      );
    }
  );
  function loadPergunta(id)
  {
    if(typeof(id)=="undefined") id = 1;
    $('#stage').fadeOut('slow');
    $.post(
      'pergunta.php',
      {id: ""+id},
      function(data) {
        if(data.toLowerCase().indexOf('input')==-1)
        {
          $("a.continuar").fadeOut("slow");
        }
        $('#pergunta').html(data).fadeIn('slow');
      }
    );
  }
</script>

<div id="box">
  <fieldset id="pergunta"></fieldset>
  <a class="continuar">Continuar &rarr;</a>
</div>

和pergunta.php:

<?php
  $p_id = (int)($_POST['id']);
  $perguntas = array
  (
    1 => array
    (
      'type' => 's_ou_n',
      'text' => 'Você está satisfeito com os seus resultados atuais?'
    ),
    array 
    (
      'type' => 's_ou_n',
      'text' => 'Você recommendará nossos servicos aos seus amigos?' 
    ),
    array
    (
      'type' => 'text',
      'text' => 'Algo mais que quer compartilhar?'
    )
  );
  $content = '';
  if($p_id<=count($perguntas)) 
  {
    if($perguntas[$p_id]['type']=='s_ou_n')
    {
      $content = '<div class="pergunta-text">'.$perguntas[$p_id]['text']."</div>'n";
      $content .=
      '
      <input type="radio" id="p_'.$p_id.'_s" name="p_'.$p_id.'" value="s"><label for="p_'.$p_id.'_s">Sim</label>
      <input type="radio" id="p_'.$p_id.'_n" name="p_'.$p_id.'" value="n"><label for="p_'.$p_id.'_n">Nao</label>
      ';
    }
    else
    {
      $content =
      '
        <label for="p_'.$p_id.'" class="pergunta-text">'.$perguntas[$p_id]['text'].'</label> <input type="'.$perguntas[$p_id]['type'].'" id="p_'.$p_id.'" name="p_'.$p_id.'" ></input>
      ';
    }
  }
  else $content = 'Obrigado pela participação!';
  echo $content;
?>

尝试jQuery live方法!

//form.js//

$(document).ready(function() {
  $('a.continue_r').live("click",function(event) {
    var id_p=$('input:radio:first').attr("name")
    var v_r=$('input:radio:checked').val();
    $.post(
        'form.php',
        { id_p:id_p, v_r:v_r },
        function(data) {
            alert('Return:'n' + data);
            $('#stage').html(data).fadeIn('slow');
            $('#stage').css('display','block');
            $('label').css('display','block');
        }
    );
  });
});