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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵