使用Ajax和PHP从行中提取值

时间:2013-05-09 14:57:20

标签: php javascript ajax dom

我从迄今为止学到的关于Ajax + Javascript的内容创建了这个小脚本。 我在Chrome btw中运行此功能,因此XMLHttpRequest();应该正常工作

PHP,     

    $conn = new PDO('mysql:host=localhost; dbname=test', 'root', '')

    $stmt = $conn->query("SELECT text FROM ajax");
    foreach($stmt as $each){

?>

的Ajax,

<script type='text/javascript'>

    var request = new XMLHttpRequest();
    request.open('GET', <?php echo $each['text']; ?>, false);
    request.send();
    console.log(request);

</script>
<?php } ?>

现在,在数据库test中,tbl名称为ajax我有行id&amp; text,其中text有三个填充行,但ajax代码没有向我显示任何内容。当我在我的行中添加文本时,它根本不回应任何东西,更不用说立即更新了。我究竟做错了什么?

2 个答案:

答案 0 :(得分:1)

<强> out.php

<?php
     $conn = new PDO('mysql:host=localhost; dbname=test', 'root', '')

     $stmt = $conn->query("SELECT text FROM ajax");
     echo json_encode($stmt);
?>

<强>的test.html

<script>
    var request = new XMLHttpRequest();
    request.open('GET', "http://mysite.com/out.php", false);
    request.onreadystatechange=function()
    {
        if (request.readyState==4 && request.status==200)
        {
             var data = JSON.stringify(request.responseText); //The data from the server will be in responseText
             //data now contains an array of JSON objects of your data
             for(i=0;i<data.length;i++) {
                 console.log(data[i].text);   //.text is a variable based on your MYSQL field
             }
        }
    }
    request.send();
    console.log(request);
</script>

首先你需要制作一个PHP脚本直接输出数据(如上面的out.php部分所示),然后将javascript脚本放在另一个页面中(如test.html部分所示)和在request.open上面的例子中给http://mysite.com/out.php调用out.php的url,但是用你的实际url替换为out.php文件,因为你在localhost上就像{{1} }

答案 1 :(得分:0)

首先,我将删除 foreach 循环。将其更改为以下内容:

echo json_encode($stmt);

这将为您的AJAX 请求变量提供一个JSON编码对象。目前,您的AJAX请求中的结果变量仅在控制台中显示结果。

也许尝试将 console.log(request)更改为以下内容:

alert(JSON.stringify(request));