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.

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

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元