使用 Ajax 和 PHP 访问 mySQL 字段


Access mySQL fields using Ajax and PHP

经过很多诱惑和阅读了很多关于我仍然无法使用Jquery读取mySQL字段的文章。我的PHP代码连接到数据库并获取一些数据,使用echo json_encode($html);输出以下内容:

{"id":"1","title":"this_is_title","description":"this_is_description","url":"this_is_url"}

然后我尝试读取单个字段,但我一直得到"未定义"。例如:

$.getJSON("get.php", function(result) {
    $.each(result, function(key, field){
         console.log(field.title);
    });
});

如果我只是使用 field 而不是field.title它就可以了,但我得到了所有字段(当然)。

如果只返回一个对象,则可以轻松访问每个字段。您已经知道字段名称,因此请使用它们。

$.getJSON("get.php", function(result) {
    console.log(result.id); 
    console.log(result.title);
    console.log(result.description);
    console.log(result.url);
});

JSON 数据仅包含一个对象,不包含对象数组。

您正在使用 $.each 迭代此 JSON 对象中的每个属性,因此在该回调函数中,key 将是属性名称,field将是属性

将控制台日志调用更改为以下内容:

console.log(field);

您可以看到差异,将记录属性的值。

您可以像这样直接访问 JSON 的属性:

$.getJSON("get.php", function(result) {
     console.log(result.id);
     console.log(result.title);
     // etc
});

试试这个,使用 parseJSON,然后尝试访问:

$.getJSON("get.php", function(result) {
    var obj = JSON.parse(result);
    $.each(obj, function(key, field){
     console.log(key); // here you will get index like id,title
     console.log(field); // here you will get value
    });
});