Ajax jquery post脚本不工作


Ajax jquery post script not working

我遵循这个教程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中包含的页面i出现问题。

这可能是因为url没有使用绝对路径。您是否在本地机器上运行此程序?这两个脚本(html和php)在同一个目录下吗?

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

您可以执行以下命令获取有关错误的更多信息:

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

错误的详细信息将出现在开发人员工具控制台中。大多数情况下,打开开发人员工具是通过在PC上按Ctrl+Shift+I或使用浏览器菜单来完成的。