2016-11-27 50 views
1

似乎這個問題已經被問了很多次,但沒有一個解決方案適用於我。我是AJAX的新手,所以我可能會錯過一些基礎知識。基本上我只是想將html段落的內容傳遞給PHP腳本,我不想使用html表單。使用AJAX後PHP中未定義的索引

我有兩個文件: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> 

和tes.php

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

我點擊發布按鈕後,在PHP文件時,它會返回

注意:未定義的索引:第3行的C:\ xampp \ htdocs \ projects \ lab \ tes.php中的文本。

它出錯了?真的需要你的幫助傢伙。謝謝!

+2

爲什麼位於tes.php中的錯誤和你鏈接test.php? – 2016-11-27 10:13:45

+0

對不起,在原來的代碼中,它實際上是鏈接到tes.php。我改變了這個問題的代碼。 – Zach

+0

那麼,未定義的索引只能表示服務器沒有收到$ _POST ['text']變量......如果刪除'$ content = $ _POST ['text'],會發生什麼? echo $ content;'並將其替換爲'print_r($ _ POST);'(僅用於調試) – 2016-11-27 10:22:31

回答

0

你可以試試這個

$(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) 
     } 
     }); 
    }); 
}); 

,並在HTML(如禮建議)

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

然後,打開開發者控制檯,看看你能看到從tes.php響應

+1

嗨@Christian!是的,我可以看到迴應。非常感謝!還要感謝@reza – Zach

0

改變HTML

<a href="tes.php" target="_blank"><button id="post2">post 2</button></a> 

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

嗨Reza ..這沒有工作......無論如何感謝 – Zach

0

你有一個click事件,併發送一個AJAX請求到目前爲止,一切都很好。您有

target="_blank" 

它確保頁面在另一個選項卡/窗口中打開。據我瞭解,你只需要發送請求,所以你需要阻止默認:

<!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(e){ 
      e.preventDefault(); 
      var getContent = $("#text").html(); 
      $.ajax({ 
      url:"tes.php", 
      type:"POST", 
      data:{text:getContent} 
      }); 
     }); 
    }); 
</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> 

的新標籤/窗口會給你的錯誤,因爲預期的參數是不存在的,所以不要」打開它。