我试图在 2 小时内解决这个问题,但运气不佳,也许这不是那么技术性,但我需要帮助!
我有一个 AJAX 脚本,需要将 GET 请求发送到同一页面上的 php 脚本。 PHP 脚本这样终止
if ($success) {
print( $state );
}?>
Javascript 就在 php 终止符下,是这样的。
<script>
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
我不明白的是为什么我会收到包含此文本的警报
inside // this is the state, so it's good
<script> // this is the script, not good
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
我必须在成功时操作 HTML,但由于我从我的 PHP 代码中获得的困惑响应,我无法做到这一点。我不确定我是否必须发布其他代码。如果您需要了解更多信息,请提问,我会尽快回复。
最佳答案
<?php ?>
之外的任何字符标签在响应中发回。这就是你如何得到 <script>
从浏览器访问 index.php 时首先标记。
echo 和 print 显然也会发送数据。
所以我想你应该有那个 if($success)
在 index.php 和 exit;
的开头在里面,在print
之后.
字符外<?php ?>
由于历史和实际原因,标签作为响应的一部分发送。
在我们这个时代,将 PHP 代码与 HTML 混合是一种不好的做法(正如一些人已经在下面的评论中指出的那样)。您要么使用模板引擎(大多数人都知道 Smarty),要么使用 PHP 本身作为模板引擎。
但是“过去”PHP 开始时只是一个简单的模板引擎(没有类、外部模块、命名空间、自动加载器等),所以混合 HTML 和 PHP 基本上是这种语言的目的.
正如我所说,今天我们仍然使用 PHP 作为模板语言,因此可以混合使用 PHP(控制结构、循环)和 HTML。
关于php - 为什么PHP对AJAX的响应包含<script> aBunchOfJavascriptHere </script>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18419577/