douzhang1955 2016-11-27 10:12
浏览 42
已采纳

使用AJAX后PHP中未定义的索引

It seems that this question has already been asked many times but none of the solution is working for me. I'm new to AJAX so maybe there are some basics that I've missed? Basically I just want to pass the content of an html paragraph to a PHP script and I don't want to use html form.

I have two files: tes.html

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
       $("#post").click(function(){
          var getContent = $("#text").html();
          $.ajax({
             url:"tes.php",
             type:"POST",
             data:{text:getContent},
             dataType:"html",
          });
       });
     });
</script>
</head>
<body>
    <p id="text" contenteditable="true">This is the content</p>
    <a href="tes.php" target="_blank"><button id="post">post 2</button></a>
</body>
</html>

and tes.php

<?php
    if (isset($_POST['text'])) {
        $content = $_POST['text'];
        echo $content;
    } else {
        echo "no content";
    }
?>

After I clicked the Post button, in the PHP file it returns

Notice: Undefined index: text in C:\xampp\htdocs\projects\lab\tes.php on line 3.

Where did it go wrong? Really need your help guys. Thanks!

  • 写回答

3条回答 默认 最新

  • dongxu7121 2016-11-27 11:25
    关注

    can you try this

      $(document).ready(function(){
       $("#post").click(function(){
          var getContent = $("#text").html();
          $.ajax({
             url:"tes.php",
             type:"POST",
             data:{text:getContent},
             dataType:"html",
             success:function(data) {
              console.log(data)
             }
          });
       });
     });
    

    and in the HTML (as reza suggested)

    <button id="post">post 2</button>
    

    then, open the developer console and see if you can see the response from the tes.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: