duancongjue9202
duancongjue9202
2017-03-25 15:24

如何使用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 dtml3340 4年前

    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.

    点赞 评论 复制链接分享