gpt4 book ai didi

javascript - 如何使用 jquery/ajax 运行简单的 php 代码?

转载 作者:行者123 更新时间:2023-12-01 03:11:27 25 4
gpt4 key购买 nike

因为我的实际示例太大,所以我做了一个非常简短的示例:

test1.php

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <!--jQuery-->
<body>
<p> What is the first letter of the alphabet?</p>
<button type="button" id="button">Tell me!</button>
<div id="div"></div>
<script>
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
success: function() {
$('#div').html();
}
});
});
});
</script>
</body>
</html>

test2.php

<?php
echo "It's the letter A!";
?>

我想打印出“It's the letter A!”当我按下按钮时,这似乎不起作用。有人可以帮我告诉我为什么这不起作用以及如何解决它吗?
谢谢

最佳答案

1st : 应用引号括起来 $('#button')

第二:在成功函数中获取响应,如下所示。

success: function(res) {

$('#div').html(res);

}

第三:将数据类型设置为文本。

 dataType:'text'

更新 1:

$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
dataType:'text',
success: function(res) {

$('#div').html(res);

}
});
});
});

关于javascript - 如何使用 jquery/ajax 运行简单的 php 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45813338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com