使用ajax打印“;你好,世界";当你点击一个按钮时


Using ajax to print "Hello World!" when you click a button

当你点击一个按钮时,我正试图使用ajax打印"Hello World!",但由于某种原因,它不起作用。我做错了什么?

test1.php

#testID {
border: 1px solid purple;
height: 50%;
width: 50%;
}
<?php
$commentID = "commentID";
$comment = "comment";
echo "
<input  type = 'submit' value = 'Post' onclick = '"ajaxPass('test2.php', $comment, $commentID,'testID')'">
<div id = 'testID'></div>
";
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script type = "text/javascript"> 
function ajaxPass(action,comment,commentID,outputID) {
$.ajax({
type: "POST",
url: action,
data: { comment: comment, commentID: commentID },
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById(outputID).innerHTML = data;        
} //end of success:function(data)
}); //end of $.ajax({
} //end of function ajaxPass(action,comment,commentID,outputID)
</script>

test2.php

<?php
echo "Hello World!";
?>

您的代码中存在语法错误。您的echo语句应该是这样的:

echo "<input  type = 'submit' value = 'Post' onclick = '"ajaxPass('post.php', '{$comment}', '{$commentID}','testID')'"><div id = 'testID'></div>";

在浏览器上使用ctrl+u查看源代码,并检查onclick属性中的内容。

并在test1.php页面中添加这个div <div id="outputID"></div>