duancongjue9202 2017-03-25 15:24
浏览 47
已采纳

如何使用AJAX从PHP文件中检索多个数据?

I'm working on a project where I have an HTML file with 2 different divs: "product" and "price". The text inside these divs must come from a row into a database. I can easily access these text values with a php file. I'm also able to get just one of them using AJAX and I can put it inside one of the divs. The problem is I don't know how I can get both product and price and put them inside the divs. I've found some very similar questions but none of the answers have worked for me.

Here is the JS code that I have:

$.ajax({
    type: "GET",
    url: "url to the php file",             
    dataType: "html",                
    success: function(response){                    
        $("#product").html(response);
    }
});

Here is the php (the columns I have are just id, product and price):

mysqli_query($link, $query);
$query = "SELECT * FROM products WHERE id = 1";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_array($result)) {
        echo "{$row['product']}";
    }
}

As I said, the code above works, but only for "product". I want to get both "product" and "price". I really appreciate any help you can provide.

  • 写回答

1条回答 默认 最新

  • dtml3340 2017-03-25 15:35
    关注

    You need to use JSON. Here is a simple example:

    $.ajax({
        type: "GET",
        url: "url to the php file",             
        dataType: "html",                
        success: function(response){                    
            $("#name").html(response.name);
            $("#shoes").html(response.large);           
        },
        dataType: 'json'
    });
    

    And then in the PHP to return back JSON use this approach:

    $array = array('name' => 'Bob', 'shoes' => 'large');
    echo json_encode($array);
    

    You can amend my PHP so you return back whatever you query from your database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现
  • ¥15 vscode的红色箭头爆红和has no default export报错
  • ¥15 关于#sql#的问题:#情况描述 在用vs对项目进行调试时,出现找不到网络路径,然后查看SQL配置工具,发现SQL服务显示远程调用过程失败(相关搜索:防火墙)
  • ¥15 eNSP中基于默认路由及浮动路由的公司与分部互联和校园网综合项目
  • ¥15 主要进行描述泥浆在管路不同区段泥浆的密度不相同,泥浆的密度有高有低,此时管路的摩阻分布需要怎么计算,(标签-matlab)
  • ¥40 通过编制程序计算圆管内层流充分发展对流换热,参数如图5-4,以及公式5-16所示,要求用表5-6对程序计算准确性进行验证
  • ¥20 该学习哪个编程语言? AI会取代程序员吗?
  • ¥15 ensp如何拼通IP地址
  • ¥15 saber软件导入Ibis模型报错