gpt4 book ai didi

php - Ajax jquery post 脚本不工作

转载 作者:行者123 更新时间:2023-11-29 20:32:38 26 4
gpt4 key购买 nike

我正在关注本教程 https://openenergymonitor.org/emon/node/107 。我想做的是,使用 jquery 和 php 从 mysql 数据库获取数据。我完全按照教程所说的做了,但我无法让它工作。当我加载页面时,我收到失败警报。

这就是我所做的:

api.php:

$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");

$selected = mysql_select_db($db,$dbhandle)
or die("Could not select examples");

$result = mysql_query("SELECT * FROM todolist");
$array = mysql_fetch_row($result);

echo json_encode($array);

(我知道最好使用PDO,但这只是为了测试。)

jquery 脚本:

  <script language="javascript" type="text/javascript">
$(function () {
$.ajax({
url: 'api.php', data: "", dataType: 'json',
success: function(data) {
var id = data[0];
var description = data[1];
$('#output').html("<b>id: </b>"+id+"<b> description: </b>"+description);
},
error: function() {
alert("Fail");
}
});
});
</script>

当我访问 api.php 时,我得到的是:

["161","true","werken\n","12"]

当我使用 console.log(arguments) 时,会显示:

[Object, "parsererror", SyntaxError: Unexpected token < in JSON at position 0 at Object.parse (native) at parseJSON …]
0
:
Object
1
:
"parsererror"
2
:
SyntaxError: Unexpected token < in JSON at position 0 at Object.parse (native) at parseJSON (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:16:11709) at b$ (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:16:1382) at w (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:18:8326) at XMLHttpRequest.d (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:18:14247)
callee
:
(err)
length
:
3
Symbol(Symbol.iterator)
:
values()
__proto__
:
Object

我现在正在努力完成这个工作大约 3 个小时,这让我非常疯狂。我希望有人能用我的脚本解释这个问题。

编辑:

我修好了。我包含在 api.php 中的页面有问题。

最佳答案

这可能是因为 url 没有使用绝对路径。您在本地计算机上运行它吗? 2 个脚本(html 和 php)是否位于同一目录中?

您应该尝试使用浏览器的开发者工具来检查和跟踪网络ajax调用。您可能会收到 404 错误。

您可以通过执行以下操作获得有关错误的更多信息:

error: function(err) {
console.log(err);
}

错误的详细信息将显示在您的开发人员工具控制台上。大多数时候,打开开发者工具是通过在 PC 上按 Ctrl+Shift+I 或使用浏览器菜单来完成的。

关于php - Ajax jquery post 脚本不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961220/

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