【问题标题】:Using ajax to print "Hello World!" when you click a button使用 ajax 打印“Hello World!”当你点击一个按钮
【发布时间】:2016-01-01 22:19:02
【问题描述】:

我正在尝试使用 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!";

?>

【问题讨论】:

  • 您的 onclick 属性的语法错误。在你的网页上做一个查看源代码,看看它是如何输出的。

标签: javascript php jquery ajax


【解决方案1】:

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

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

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

并在您的 test1.php 页面中添加此 div &lt;div id="outputID"&gt;&lt;/div&gt;

【讨论】:

  • 等等。您的意思是唯一的部分是您必须在回显它们时将 php 变量括在括号和单引号中?!!!!
  • @frosty 是的,就是这样。
  • 我想尖叫。我一直在花费数小时试图找出我错在哪里......谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-02-28
  • 2012-10-06
  • 2018-03-11
  • 2014-01-10
  • 1970-01-01
  • 2017-09-29
  • 2015-05-04
  • 1970-01-01
相关资源
最近更新 更多