-1

我正在制作一个用户名检查器,它接受 POST 数据并将其发送到 PHP 脚本,该脚本创建一个简单的数组(现在只有 2 个键),该数组被传回 jQuery 并将其回显到<p>标签中。我可以通过写入所有数据来调用它,但是每当我尝试访问数据中的单个键(请记住它是一个数组)时,它只会返回空白或}. 这是我的代码。

HTML/JavaScript

<!DOCTYPE html>
<html lang='en'>
    <head>
        <title>Username Checker</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    </head>
    <body>
        <center>
            <h1>Username Checker</h1>
            <input type="text" id="name" />
            <input type="button" value="Submit" id="submit" />
            <br />
            <br />
            <hr />
            <br />
            <p id="status"></p>
        </center>

        <script type='text/javascript'>
            $('input#submit').on('click', function() {
                var name = $('input#name').val();
                if ($.trim(name) != '') {
                    $.post('status.php', {name: name}, function(data) {
                        document.getElementById('status').innerHTML= data[0];
                    });
                }
            });
        </script>
    </body>
</html>

状态.php

<?php
function remoteStatusCode($url){
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL,$url );
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch,CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch,CURLOPT_SSLVERSION,3);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpcode == 404) {
        $httpcode = "<span style='color:red;'>".$httpcode;
        $httpcode .= "</span>";
    }
    else {
        $httpcode = "<span style='color:green;'>".$httpcode;
        $httpcode .= "</span>";
    }
    return $httpcode;
}

$name = $_POST['name'];

$status = array(
    'youtube' => remoteStatusCode('https://www.youtube.com/user/'.$name),
    'deviantart' => remoteStatusCode('http://'.$name.'.deviantart.com/'),
);

echo json_encode($status, JSON_UNESCAPED_SLASHES);
?>

请不要告诉我我的代码容易受到攻击或任何东西,因为我完全知道我没有添加任何检查,因为它仍处于测试阶段,我还没有发布它的计划。

4

1 回答 1

0

http://api.jquery.com/jQuery.parseJSON/

在 post 回调中,尝试在访问数据之前将响应显式转换为 json。php 没有将内容类型设置为 application/json (请参阅:https ://stackoverflow.com/questions/267546/correct-content-type-http-header-for-json ),因此结果只是一个字符串.

$.post('status.php', {name: name}, function(data){
    var obj = $.parseJSON(data);
    document.getElementById('status').innerHTML= obj.youtube; 
});
于 2013-09-28T22:09:28.290 回答