单击按钮从PHP文件中获取数据

时间:2022-10-09 03:37:30

When you load the page, I have two separate divs that get images randomly from a database then echo them as the background-image. I also get other data that comes along with the image.

当你加载页面时,我有两个独立的div,它们从数据库中随机获取图像,然后将它们作为背景图像回显。我还获得了图像附带的其他数据。

I need to get data from a new PHP file and change the background-image of a div on click of a button (so that you don't need to refresh the page).

我需要从新的PHP文件中获取数据,并在单击按钮时更改div的背景图像(这样您就不需要刷新页面)。

In getnew.php:

$select = mysqli_select_db($conn, "database"); 

$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$img1link = $row['link'];
$rating1 = $row['rating'];
$s1 = $row['sigma'];

$result2 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
$rating2 = $row2['rating'];
$s2 = $row2['sigma'];

In main.php:

$("#button").on("click",function(){
    //
})

As I understand it you use jQuery's $.get to fetch the data from getnew.php but how exactly can I then use the data to change the background-image without having to refresh the page?

据我所知,你使用jQuery的$ .get从getnew.php获取数据但是我怎样才能使用数据来更改背景图像而不必刷新页面?

For example: style="background-image: url('<?php echo $img1link ?>')">

例如:style =“background-image:url(' ')”>

3 个解决方案

#1


You'll need to use ajax, send data from the server and parse it at the client

您需要使用ajax,从服务器发送数据并在客户端解析它

Here is a code sample based on your snippet

以下是基于您的代码段的代码示例

In getnew.php:

$select = mysqli_select_db($conn, "database"); 
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$img1link = $row['link'];
$rating1 = $row['rating'];
$s1 = $row['sigma'];
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
$rating2 = $row2['rating'];
$s2 = $row2['sigma'];
echo json_encode(array('img1'=>$img1link,'img2'=>$img2link));

In main.php:

$("#button").on("click",function(){
    $.getJSON("getnew.php",function(data){
    //use data.img2 and data.img1 and set the background
    // for example: $('#someDiv').css('background-image',"url('"+data.img1+"')");
   });
})

#2


use JQuery CSS codes..as you are able to fetch the data from a page, pass the image path in jquery.css code, it will do as per your desire.

使用JQuery CSS代码。如果你能够从页面获取数据,在jquery.css代码中传递图像路径,它将按照你的愿望。

Try to analyze the code

尝试分析代码

Place it in a finction which will be called on click of the function: on success you may use css like code: This is just an example in ajax/jquery

将它放在一个将在点击该函数时调用的finction:成功时你可以使用css代码:这只是ajax / jquery中的一个例子

 $.ajax("signin.php", {
                            data: {
                                login:  login,
                                pass:   pass
                            },
                            success: function(data)
                            {
                                //alert(data);
                                if (data==1)
                                {
                                    s$("#login").animate({   opacity: 1,top: '49%' }, 200,function(){
         $('.userbox').show().animate({ opacity: 1 }, 500);
            $("#login").animate({   opacity: 0,top: '60%' }, 500,function(){
                $(this).fadeOut(200,function(){
                  $(".text_success").slideDown();
                  $("#successLogin").animate({opacity: 1,height: "200px"},500);                  
                });                           
             }) 
     }) 

                                }
                                else
                                {
                                    alert(data);
                                    setTimeout( "unloading()", 1000 );
                                    showError('OOPS..please check the credentials..');
                                }
                            },
                            error: function()
                            {
                                //alert(data);
                                showError('OOPS..Error in Connection..');
                            },
                            type: "POST"
                      });

#3


Just a quick script, but hope it helps:

只是一个快速的脚本,但希望它有所帮助:

in getnew.php

$select = mysqli_select_db($conn, "database"); 
function get_random_image(){
    $result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
    $row = $result->fetch_assoc();
    $result=[
        'link' => $row['link'],
        'rating' => $row['rating'],
        'sigma' => $row['sigma'] 
        ];
    return $result;
}

if($_POST['request']=='get_random_image'){
    $r = array();
    array_push($r, get_random_image());
    array_push($r, get_random_image());

    echo json_encode($r);
}

in javascript file:

在javascript文件中:

$("#button").on("click",function(){
    show_image();
})

function show_image(){
    var response = get_data("get_random_image");

    response = jQuery.parseJSON(response);
    $.each( response, function( key, value ) {
        // do something with the data like this:
        $('.image').append('<img src="'+value.link+'">');
    }
}

function get_data(requested_action)
{
    var data=$.ajax({
        type: "POST",
        url: '../getnew.php',  // relative path to the php file
        data: {
            request:requested_action
        }, 
        async: false,
        dataType: 'json'
    });
    var msg= data.responseText;
    return msg;
}

#1


You'll need to use ajax, send data from the server and parse it at the client

您需要使用ajax,从服务器发送数据并在客户端解析它

Here is a code sample based on your snippet

以下是基于您的代码段的代码示例

In getnew.php:

$select = mysqli_select_db($conn, "database"); 
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$img1link = $row['link'];
$rating1 = $row['rating'];
$s1 = $row['sigma'];
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
$rating2 = $row2['rating'];
$s2 = $row2['sigma'];
echo json_encode(array('img1'=>$img1link,'img2'=>$img2link));

In main.php:

$("#button").on("click",function(){
    $.getJSON("getnew.php",function(data){
    //use data.img2 and data.img1 and set the background
    // for example: $('#someDiv').css('background-image',"url('"+data.img1+"')");
   });
})

#2


use JQuery CSS codes..as you are able to fetch the data from a page, pass the image path in jquery.css code, it will do as per your desire.

使用JQuery CSS代码。如果你能够从页面获取数据,在jquery.css代码中传递图像路径,它将按照你的愿望。

Try to analyze the code

尝试分析代码

Place it in a finction which will be called on click of the function: on success you may use css like code: This is just an example in ajax/jquery

将它放在一个将在点击该函数时调用的finction:成功时你可以使用css代码:这只是ajax / jquery中的一个例子

 $.ajax("signin.php", {
                            data: {
                                login:  login,
                                pass:   pass
                            },
                            success: function(data)
                            {
                                //alert(data);
                                if (data==1)
                                {
                                    s$("#login").animate({   opacity: 1,top: '49%' }, 200,function(){
         $('.userbox').show().animate({ opacity: 1 }, 500);
            $("#login").animate({   opacity: 0,top: '60%' }, 500,function(){
                $(this).fadeOut(200,function(){
                  $(".text_success").slideDown();
                  $("#successLogin").animate({opacity: 1,height: "200px"},500);                  
                });                           
             }) 
     }) 

                                }
                                else
                                {
                                    alert(data);
                                    setTimeout( "unloading()", 1000 );
                                    showError('OOPS..please check the credentials..');
                                }
                            },
                            error: function()
                            {
                                //alert(data);
                                showError('OOPS..Error in Connection..');
                            },
                            type: "POST"
                      });

#3


Just a quick script, but hope it helps:

只是一个快速的脚本,但希望它有所帮助:

in getnew.php

$select = mysqli_select_db($conn, "database"); 
function get_random_image(){
    $result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
    $row = $result->fetch_assoc();
    $result=[
        'link' => $row['link'],
        'rating' => $row['rating'],
        'sigma' => $row['sigma'] 
        ];
    return $result;
}

if($_POST['request']=='get_random_image'){
    $r = array();
    array_push($r, get_random_image());
    array_push($r, get_random_image());

    echo json_encode($r);
}

in javascript file:

在javascript文件中:

$("#button").on("click",function(){
    show_image();
})

function show_image(){
    var response = get_data("get_random_image");

    response = jQuery.parseJSON(response);
    $.each( response, function( key, value ) {
        // do something with the data like this:
        $('.image').append('<img src="'+value.link+'">');
    }
}

function get_data(requested_action)
{
    var data=$.ajax({
        type: "POST",
        url: '../getnew.php',  // relative path to the php file
        data: {
            request:requested_action
        }, 
        async: false,
        dataType: 'json'
    });
    var msg= data.responseText;
    return msg;
}