使用jQuery发布HTML内容的问题 - Ajax Post方法

时间:2014-04-25 19:17:48

标签: php jquery ajax

我正在尝试使用jquery ajax将div部分发布到新页面:

<!DOCTYPE html>
<body>
  <div id="edit_content">
    <p>This is a test</p>    
   </div>
  <a href="out.php" id="submit_script">Submit</a>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script>
   $( document ).ready(function() {
          var htmlData = $('#edit_content').html();
         $.post('out.php', {'html': htmlData },function(){
      });
   });
</script>
</body>
</html>

并在out.php页面中:

<?php
$content = $_POST['html'];
echo $content;

但是当我运行代码时,我收到此错误:

  

注意:未定义的索引:第2行的G:\ Apps \ out.php中的html

你可以告诉我为什么会这样,我怎么能阻止它?

3 个答案:

答案 0 :(得分:1)

您的$.post函数在数据字段中有拼写错误,请尝试此操作:

$.post('out.php', {html: htmlData }, function(response){

由于您发送的是对象,因此该密钥不需要引号。

或者更好,但是你的所有数据都在你的帖子中引用它们:

var postData = {html: $('#edit_content').html() }
$.post('out.php', postData, function(response){

答案 1 :(得分:1)

您的代码按原样运行 - 至少就帖子而言。为了说明这一点,将其更改为以下内容(唯一的变化是实际上对ajax请求的响应做了一些事情):

<!DOCTYPE html>
<body>
  <div id="edit_content">
    <p>This is a test</p>    
   </div>
  <a href="out.php" id="submit_script">Submit</a>

  <div id="out"></div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script>
  $( document ).ready(function() {
        var htmlData = $('#edit_content').html();
        $.post('out.php', {'html': htmlData }, function(data){  
            $('#out').html(data);
        });
  });
</script>
</body>
</html>

我认为你需要解释你尝试做什么(或者你期望看到的)。正如您的代码所示,您一旦页面加载(在文档就绪)但是没有对响应做任何事情,就会运行ajax请求。然后,您有一个指向out.php(<a href="out.php" id="submit_script">Submit</a>)的链接。当您点击链接时,您是否希望在out.php中看到结果?如果是这样,那就不会发生。发生的事情是,当页面加载时,它会使用post数据向out.php运行请求并获得响应(然后忽略)。当您点击链接时,您运行新请求到out.php 而不发布数据,这样您什么也看不见。

如果我猜对了,那么你想要用点击链接触发的表单提交替换链接(首先获取数据)。像

这样的东西
<!DOCTYPE html>
<body>
  <div id="edit_content">
    <p>This is a test</p>    
   </div>
  <a href="#" id="submit_script">Submit</a>

  <form action="out.php" method="post" id="out-form"  style="display: none;">
    <input type="hidden" id="hidden-html" name="html" value="" />
  </form>  

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script>
  $( document ).ready(function() {
        $('#submit_script').click(function(){
            $('#hidden-html').val($('#edit_content').html());
            $('#out-form').submit();
            return false;
        })
  });
</script>
</body>
</html>

答案 2 :(得分:0)

'html'数据未发布到您的php页面。将您的php文件更改为:

<?php
  if(isset($_POST['html']))
  {
    $content = $_POST['html'];
    echo $content;
  }
?>

这应该可以阻止错误并至少指向正确的方向。如果没有更多代码,我无法告诉您为什么没有发布'html'数据。