我正在尝试使用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!";
?>
答案 0 :(得分:2)
您的代码中存在语法错误。您的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>
。