验证嵌套ajax调用的json响应

时间:2013-11-03 06:50:37

标签: php ajax json

我在这里测试了我的jsno示例:

data.php

<?php

ob_start();
echo "string1";
$div1 = ob_get_clean();
ob_start(); 
echo "string2";
$div2 = ob_get_clean();

$resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
echo json_encode($resultArray);

?>

start.php

xmlhttp.onreadystatechange=function()
                {
                    var div1=document.getElementById("myDiv1");
                    var div2=document.getElementById("myDiv2");
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        var data=JSON.parse(xmlhttp.responseText);
                        //document.getElementById("myDiv1").innerHTML=xmlhttp.responseText;
                        div1.innerHTML=data['resultOne'];
                                    div2.innerHTML=data['resultTwo'];
                    }
                }

这样可以得到正确的结果并显示数据。

现在我尝试在我的实际应用程序上实现。

login.php(验证用户登录,如果成功) - &gt; start.php(通过ajax加载到login.php) - &gt; data.php(返回json数组值,如上例所示)

唯一不同的是data.php采用以下方式:

<?php
    $url = $_POST['url'];
    $user_id = $_POST ['userid'];
    if(isset($_POST['rate']))
    {
        $rate =$_POST['rate'];
    }
    else
        $rate = 0;
    $data = file_get_contents($url);
    function get_title($html) 
    {
        return preg_match('!<title>(.*?)</title>!i', $html, $matches) ? $matches[1] : '';
    }

    function get_logo($html) 
    {
        preg_match_all('/\bhttps?:\/\/\S+(?:png|jpg)\b/', $html, $matches);
        //echo "mactch : $matches[0][0]";
        return $matches[0][0];  
    }   

    function plaintext($html)
    {
        // remove comments and any content found in the the comment area (strip_tags only removes the actual tags).
        $plaintext = preg_replace('#<!--.*?-->#s', '', $html);

        // put a space between list items (strip_tags just removes the tags).
            $plaintext = preg_replace('#</li>#', ' </li>', $plaintext);

            // remove all script and style tags
        $plaintext = preg_replace('#<(script|style)\b[^>]*>(.*?)</(script|style)>#is', "", $plaintext);

        // remove br tags (missed by strip_tags)
            $plaintext = preg_replace("#<br[^>]*?>#", " ", $plaintext);

            // remove all remaining html
            $plaintext = strip_tags($plaintext);

        return $plaintext;
    }

    function trim_display($size,$string)
    {
        $trim_string = substr($string, 0, $size);

        $trim_string = $trim_string . "...";
        return $trim_string;
    }

    $title = get_title($data);
    $logo = get_logo($data);
    $title_display = trim_display(30,$title);
    $content = plaintext($data); 
    $Preview = trim_display(100,$content); //to Show first 100 char of the web page as preview

    function MakeTinyUrl($url)
    {
        return md5($url);
    }

    $hash = MakeTinyUrl($url);
    ob_start(); 
    $con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        return;
    }

    $content=mysqli_real_escape_string($con,$content);
    $Preview=mysqli_real_escape_string($con,$Preview);
    $title_display=mysqli_real_escape_string($con,$title_display);

    $result = mysqli_query($con,"SELECT COUNT(*) as val FROM post_data WHERE url ='".$url."' and userid='".$user_id."'");
    $bool= mysqli_fetch_assoc($result); 
    if($bool['val'])
    {
        echo '<div style="clear:both;"><i>You have already worked on this url..</i> </div>';
    }
    else
    {
        $insertQuery = "INSERT INTO post_data(`userid`, `url`, `desc`, `preview`, `img_url`, `title` ,`hash`) VALUES ('".$user_id."','".$url."','".$content."','".$Preview."','".$logo."','".$title_display."','".$hash."')";
        if (!mysqli_query($con,$insertQuery))
        {
            die('Error: ' . mysqli_error($con));
        }
    }

    $result = mysqli_query($con,"SELECT * FROM post_data WHERE userid ='".$user_id."' and url='".$url."'");
    //This will fetch only one row from db
    while ($row = @mysqli_fetch_array($result))
    {
        $title = $row['title'];
        $url = $row['url'];
        $preview = $row['preview'];
        $image = $row['img_url'];       
    }
    //Update Rate value in table
    $update = "update post_data set rate='".$rate."' where url='".$url."'";
    if (mysqli_query($con, $update))
    {
        //echo "updated";
    }
    else
    {
        //echo "Not updated";
    } 

?>
<html>
<body>  
    <a class="fragment" href="google.com">
        <div>
            <span id='close' onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span>
            <img src ="<?php echo $image ?>" height="116" width="116" alt="some description"/>
            <h3><?php echo $title ?></h3>
            <h4><?php echo $url ?> </h4>
            <p class="text"> <?php echo $preview ?> 
                </p>

        </div>
    </a>

    <?php
        $div1 = ob_get_clean();
        ob_start(); 
        $result = mysqli_query($con,"SELECT * FROM post_data WHERE userid ='".$user_id."'");
        echo "Records for user : $user_id"; echo "<br/>";
        while ($row = @mysqli_fetch_array($result))
        {
            $title = $row['title'];
            $url = $row['url'];
            $preview = $row['preview'];
            $image = $row['img_url'];       
            echo "Title: $title"; echo '<br/>';
            echo "URL: $url";  echo '<br/>';
            echo "Preview : $preview"; echo '<br/>';
            echo "Image url: $image"; echo '<br/>';
            //echo '</br>';
        }     
        $div2 = ob_get_clean();
        $resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
        echo json_encode($resultArray);

    ?>


</body>
</html>

我收到错误消息:

SyntaxError:JSON.parse:JSON数据后的意外非空白字符

var data = JSON.parse(xmlhttp.responseText);

1 个答案:

答案 0 :(得分:1)

您可以使用以下网址验证您的json回复,以便您可以在某些方面结束您的结果,

    $resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
    echo json_encode($resultArray);

参考:http://jsonformatter.curiousconcept.com/#jsonformatter