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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!