似乎已经多次询问过这个问题但是没有一个解决方案适合我。我是AJAX的新手,所以也许我错过了一些基础知识?基本上我只想将html段落的内容传递给PHP脚本,我不想使用html表单。
我有两个文件: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";
}
?>
点击Post按钮后,在PHP文件中返回
注意:未定义的索引:第3行的C:\ xampp \ htdocs \ projects \ lab \ tes.php中的文本。
哪里出错了?真的需要你的帮助。谢谢!
答案 0 :(得分:0)
更改html
<a href="tes.php" target="_blank"><button id="post2">post 2</button></a>
到
<button id="post">post 2</button>
答案 1 :(得分: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>
新的标签/窗口会显示错误,因为预期的参数不存在,所以不要打开它。
答案 2 :(得分: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中(如reza建议的那样)
<button id="post">post 2</button>
然后,打开开发人员控制台,看看是否可以看到tes.php的响应