dongshanxun6479 2015-08-05 06:57
浏览 98

从数据库获取内容而不刷新页面完整脚本

I have a problem with this code I have a php code that get contents from DB I want to load this contents in a div with "link" class without refreshing page

this code

<?
include('config.php');
$rs = mysql_query("SELECT *
FROM `database` order by desc limit 1");
while($rw = mysql_fetch_assoc($rs))
    $id = $rw['id'];


$title = $rw['title'];

?>

<div class="link">
<?
echo $title;
?>

</div>

and one of members gives this code to me and told me "Script for your web page:"

{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtData").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "getData.php?q=" + str, true);
    xmlhttp.send();
}

and "then you need to create a getData.php file that does your data execution in your question and barfs it up for the ajax call to dump in the txtData control (or wherever else you want the data to go.)"

Now my problem is: I know only css and php and don't understand the above code.

Please give me a complete code and script

  • 写回答

1条回答 默认 最新

  • dongnuo6310 2015-08-05 07:08
    关注

    Put the AJAX code in a function, and call the function in your HTML page when you want to load the data from the PHP into the div tag with link class:

    function loadData(){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtData").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "getData.php?q=" + str, true);
        xmlhttp.send();
    }
    

    Quick explanation...

    var xmlhttp = new XMLHttpRequest(); creates a javascript object to perform the AJAX data transactions

    xmlhttp.onreadystatechange =... tells the webpage which function to execute when the onreadystatechange event happens

    xmlhttp.open("GET", "getData.php?q=" + str, true); this set all the information to be sent to the getData.php in the background via the GET method

    xmlhttp.send(); performs the request

    xmlhttp.readyState == 4 && xmlhttp.status == 200 is the state of the xmlhttp object when a response has been received from the PHP page

    document.getElementById("txtData").innerHTML = xmlhttp.responseText; gets the response data available in xmlhttp.responseText and sets the data in element with id txtData

    I hope this helps :)

    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本