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 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面