我试图从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>
由于无法从PHP代码中获得混乱的响应,因此我无法成功处理HTML。我不确定是否要发布其他代码。如果您需要了解更多信息,请问,我会尽快答复。
最佳答案
<?php ?>
标记之外的所有字符都将在响应中发回。这就是从浏览器访问index.php时首先获得<script>
标记的方式。
回显和打印显然也将发送数据。
因此,我想您应该在index.php的开头有if($success)
,并在exit;
之后在其中包含print
。
出于历史和实际原因,<?php ?>
标记之外的字符将作为响应的一部分发送。
在当今时代,将PHP代码与HTML混合使用是一种不好的做法(某些人已经在下面的注释中指出)。您可以使用模板引擎(大多数人都了解Smarty),也可以使用PHP本身作为模板引擎。
但是“回头看” PHP最初只是一个简单的模板引擎(没有类,外部模块,名称空间,自动加载器等),因此将HTML与PHP混合基本上是该语言的目的。
就像我说的那样,今天我们仍然使用PHP作为模板语言,因此可以混合使用PHP(控件结构,循环)和HTML。