【问题标题】:Get data from PHP file on click of a button单击按钮从 PHP 文件中获取数据
【发布时间】:2015-05-07 10:36:24
【问题描述】:

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

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

在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'];

在main.php中:

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

据我了解,您使用 jQuery 的 $.get 从 getnew.php 获取数据,但是我如何才能使用这些数据来更改背景图像而无需刷新页面?

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

【问题讨论】:

  • 如果你搜索,你会得到很多这方面的教程。

标签: php jquery


【解决方案1】:

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

这是一个基于您的 sn-p 的代码示例

在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));

在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+"')");
   });
})

【讨论】:

  • 它给了我 Uncaught syntax error: Unexpected token o as an error。
  • 如果我的回复有帮助,请投票或接受它作为答案。调试你的代码不在这个问题的范围内。
  • 现在看起来可以工作,但图像在新旧之间来回滑动
【解决方案2】:

使用 JQuery CSS 代码..因为您可以从页面中获取数据,在 jquery.css 代码中传递图像路径,它会按照您的意愿进行。

尝试分析代码

把它放在一个函数中,点击函数就会调用它: 成功后,您可以使用类似 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"
                      });

【讨论】:

  • 我不知道如何使用 $.get 来完成我正在做的事情。
  • 我试过了,但我仍然不确定。例如 W3 学校的这个:puu.sh/hEzSW/f083e3bbd4.png - 我不确定如何将其与我自己的问题联系起来。
【解决方案3】:

只是一个简短的脚本,但希望对您有所帮助:

在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);
}

在 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;
}

【讨论】:

  • 这对我来说似乎有点复杂(编码新手),Uri Goren 下面对此的回答对我来说似乎更容易得到,但它给了我一个错误。你明白为什么吗?
  • 您是否在控制台中收到错误消息?你试过console.log(数据)吗?看看你得到了什么?要查看控制台输出,请右键单击页面中的任意位置并选择检查元素(mozilla 的 firebug 扩展)
  • 他的解决方案给了我“Uncaught syntax error: Unexpected token o”作为错误。
猜你喜欢
  • 2016-03-24
  • 2019-11-30
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
相关资源
最近更新 更多