douhe4608 2014-04-18 15:38
浏览 531
已采纳

从JSON变量中获取变量

Im having some problems getting different variables from a JSON variable.

I do a $.post on get_shop.php file that gets data from a database, take the results and put it into a array and do a json_encode on it and prints it.

get_shop.php:

$id = $_GET["id"];

    $query = " 
        SELECT 
            *
        FROM shop
        WHERE 
            id = :id
    "; 

    // The parameter values 
    $query_params = array( 
        ':id' => $id
    ); 

    try 
    { 
        // Execute the query against the database 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code.  
        die("Failed to run query: " . $ex->getMessage()); 
    } 

    // Retrieve the user data from the database.  If $row is false, then the username 
    // they entered is not registered. 
    $row = $stmt->fetch(); 

    $database_data = array(
    "name" => $row["name"],
    "description" => $row["description"],
    "category" => $row["category"],
    "price" => $row["price"]
    );

    print(json_encode($database_data, JSON_UNESCAPED_UNICODE));

After that i do a console.log with the data received in shop.php (The file that makes the $.post request)

shop.php $.post sample:

$(document).ready(function(){
console.log("ID: " + id );

$.post("get_shop.php?id="+id+"",
function(data,status){

console.log(data + "
Status: " + status); )};

An example for a result:

{"name":"Hardrive 5GB","description":"Speed 10MB/s","category":"Hardrive","price":"1000"}

Now, the problem is that i want to show a part of the result (Like just "name") but it says "undefined" (I use data[name]). How do i solve this? Thanks!

  • 写回答

4条回答 默认 最新

  • dongmie3526 2014-04-18 15:43
    关注

    You need to parse the Json string first, this will convert it into an object you can then reference the individual values using obj.attribue or obj['attribute'].

    $.post("get_shop.php?id="+id+"",function(data,status){
        var obj = JSON.parse(data);
        var name = obj.name;
    });
    

    Look at @RomanHocke's answer to see other ways to allow Jquery to automatically convert the response into a javascript object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器