简体   繁体   English

使用Ajax和PHP访问mySQL字段

[英]Access mySQL fields using Ajax and PHP

After lot of temptatives and after reading lot of posts about I'm still unable to read mySQL fields using Jquery. 经过大量的尝试和阅读了很多有关的文章之后,我仍然无法使用Jquery读取mySQL字段。 My PHP code, which connects to a db and gets some data, outputs the following using echo json_encode($html); 我的PHP代码连接到数据库并获取一些数据,并使用echo json_encode($html);输出以下内容echo json_encode($html); :

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

I then try to read the single fields but I keep getting "undefined". 然后,我尝试读取单个字段,但我不断显示“未定义”。 For example: 例如:

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

If I simply use field instead of field.title it works but I get all the fields (of course). 如果我只是使用field而不是field.title那么它可以工作,但是我可以得到所有字段(当然)。

If there is only a single object returned then you can easily access each field. 如果仅返回一个对象,则可以轻松访问每个字段。 You already know the field names so use them. 您已经知道字段名称,因此请使用它们。

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

Try this, use parseJSON and then try to access : 试试这个,使用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
    });
});

Your JSON data contains only a single object, not an array of objects. 您的JSON数据仅包含一个对象,而不包含对象数组。

You are iterating over each property within this JSON object with $.each , so within that callback function key will be the property name and field will be the property value . 您正在使用$.each遍历此JSON对象中的每个属性,因此在该回调函数key中将是属性名称,而field将是属性

Change your console log call to this: 将控制台日志调用更改为此:

console.log(field);

and you can see the difference, the value will of the property will be logged. 并且您可以看到差异,该属性的值will将被记录。

You can access the properties of the JSON directly like so: 您可以像这样直接访问JSON的属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM