dongtang5057 2014-03-13 01:58
浏览 53
已采纳

AJAX将PHP数据返回到页面

Edit

I've changed my approach based on some research, and I'm getting a partial result.

Database:

+--------------------------------------------------+
|  id  |  date      |  objet  |  contenu     | lu  |
+--------------------------------------------------+
|  1   | 2013-01-20 | msg1    | msg1_content | 0   |
|  2   | 2013-01-20 | msg2    | msg2_content | 0   |
|  3   | 2013-01-20 | msg3    | msg3_content | 0   |
+--------------------------------------------------+

Link:

<a href="javascript:void(0);" onclick="markAsRead('.$message['id'].');">View'</a>

JS/AJAX:

function markAsRead(id)
{
    $.ajax(
    {
        type: "GET",
        url: 'php/messagerie.php',
        data: "id=" + id, // appears as $_GET['id'] @ ur backend side
        success: function(data)
        {
            // data is ur summary
            $('#contenu').html(data);
        }
    });
}

PHP (php/messagerie.php)

$q = intval($_GET['id']);

// connect to db (of course not shown here)
if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}

$sql="SELECT * FROM coq_messagerie WHERE id = '".$q."'";

$lu = mysqli_query($mysqli, "UPDATE ".DB_PREFIX."messagerie SET lu='1' WHERE id='$q' LIMIT 1");
$result = mysqli_query($con,$sql);

    echo "<table border='1' width='100%'>
        <tr>
            <th>id</th>
            <th>date</th>
            <th>objet</th>
            <th>contenu</th>
            <th>lu</th>
        </tr>";

        while($row = mysqli_fetch_array($result))
        {
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['date'] . "</td>";
                echo "<td>" . $row['objet'] . "</td>";
                echo "<td>" . $row['contenu'] . "</td>";
                echo "<td>" . $row['lu'] . "</td>";
            echo "</tr>";
        }

    echo "</table>";

mysqli_close($con);

I'm currently only retrieving only the <th>'s and not information when I'm looking up for id 2 or 3, but am getting information for id 1. How can this be only partially working?


Introduction

In an attempt to show dynamic information on my page, I'm using a mix of a few bits and pieces of code which should collect data from a basic HTML link which parses and returns data on the current page. Of course, this seems very basic, but being my first AJAX script, I would greatly appreciate some help.

Code

HTML Link:

$output .= '<a onclick="markAsRead('.$message['id'].'); return false;">'.View.'</a>';

Note: The link collects the id field as expected.

JS/AJAX Code:

function markAsRead(str) {
    console.log("starting");
    if (str=="")
    {
        console.log("string empty");
        document.getElementById("contenu").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        console.log("on ready state change");
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("contenu").innerHTML=xmlhttp.responseText;
        }
        else
        {
            console.log("seems to returning information");
            var abc = "<h1>Huh.</h1>";
            document.getElementById("contenu").innerHTML=abc;
        }
    }
    xmlhttp.open("GET","php/messagerie.php?q="+str);
    xmlhttp.send();
}

Note: The console.log('###_'+str) is used to see where the code crashes. All logged properly (105, 107, 109).

PHP (php/read.php)

// connect to db (of course not shown here)
$message = $GET["messageid"];

$lu = mysqli_query($mysqli, "UPDATE messages SET lu='1' WHERE id='$message' LIMIT 1");
if(!$lu)
{
    echo "Update error"; 
    exit;
}
else
{    
    $data = mysqli_query($mysqli, "SELECT * FROM messages WHERE id='$message' LIMIT 1");
    while($row = mysqli_fetch_array($data))
    {
        echo $row["contenu"];
    }
}

Note: $lu is updated, which makes me believe the problem is either in the while/echo area or in my AJAX return.

Current console logs

starting
on ready state change
seems to returning information
-> GET ***/php/messagerie.php?q=3
   ** params -> q 3 **
   ** empty response **
   ** empty HTML **
on ready state change
seems to returning information
on ready state change

Where am I going wrong?

  • 写回答

2条回答 默认 最新

  • dougan1465 2014-03-18 20:03
    关注

    Solution found! This updates the field value to mark message as read and shows the message in the proper div.

    Solution

    In the AJAX request, the missing parameter of true has been added with the query.

    Complete code

    AJAX

    function markAsRead(str)
    {    
        if (str=="")
        {
            document.getElementById("contenu").innerHTML="";
            return;
        }
        if (window.XMLHttpRequest)
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById("contenu").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","php/messagerie.php?q="+str,true);  // added ",true"
        xmlhttp.send();
    }
    

    PHP

    $q = intval($_GET['q']);
    
    $con = mysqli_connect('','','',''); // values hidden here for obvious reasons
    mysql_set_charset('utf8',$con);
    
    if (!$con)
    {
        die('Could not connect: ' . mysqli_error($con));
    }
    
    $sql="SELECT * FROM messages WHERE id = '".$q."'";
    $result = mysqli_query($con,$sql);
    
    $update = mysqli_query($con, "UPDATE messages SET lu='1' WHERE id='$q'");
    
    if(mysqli_num_rows($result) > 0)
    {
        echo "<table border='1'>
                <tr>
                    <th>id</th>
                    <th>date</th>
                    <th>objet</th>
                    <th>contenu</th>
                    <th>lu</th>
                </tr>";
    
        while($row = mysqli_fetch_array($result))
        {
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['date'] . "</td>";
                echo "<td>" . $row['objet'] . "</td>";
                echo "<td>" . $row['contenu'] . "</td>";
                echo "<td>" . $row['lu'] . "</td>";
            echo "</tr>";
        }
    
        echo "</table>";
    }
    
    mysqli_close($con);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?