2011-01-28 32 views
2

jsonでphpからjavascriptへ配列リストを転送しようとしていますが、動作しません。PHPからJavaScriptへの配列

JS:

$.ajax({ 
url: 'getProfilePhotos.php', 
type: 'post', // post or get method 
data: {}, // if you need to pass post/get parameterds you can encode them here in JSON format 
dataType: 'json', // the data type you want returned... we will use json 
success: function(responseData) { 
    var arrayList[0] = new Array(); 
    var lung = arrayList.length; 
    for(var i = 0; i<lung; i++) 
     //arrayList[i] = responseData.i; 
     console.log(responseData.i); 
}}); 

PHP:クリストファー・マッキャン私はコンソールでエラーを持っている

ため

<p> <?php 
     $array = array(); 
     $nr = count($friends['data']); 

    for($i = 0; $i < $nr; $i++){ 
     $array = 'link'=>array("http://graph.facebook.com/".$friends['data'][$i]['id']."/picture"); 
     ?> 
     <img src="http://graph.facebook.com/<?php echo $friends['data'][$i]['id'] ?>/picture" /> 
     <?php 
    } 
    header('Content-type: application/json'); 
    echo json_encode($array); 

?></p> 

を更新。これはエラーです。

[02:46:21.281]不足している} script.jsでhttp://romanager.ro/api/examples/script.js:3

ライン3 @プロパティリストは、実際には

type: 'post', // post or get method 

された後、私はFacebookのプロフィール写真から取得したいです。 PHPのスクリプトで私は写真を取得することができたが、私はPHPからjavascriptにIDを転送することができます。必要ならば、私はPHPスクリプトとjavascriptファイル全体を書き込もうとします。

アップデートはまだこれらのスクリプトに問題があります。私はfacebookでユーザーのIDを取得する必要があるため、彼の友達のIDを取得するためにPHPスクリプトでは、私はやFacebookのユーザーの認証を行います。ログインするにはPHPスクリプトでhtmlを作成する必要があります。私はスクリプトのコードを投稿し、あなたが私を助けてくれることを願っています。

PHPスクリプト:あなたはまだというだけでJSONよりも、HTMLを生成しようとしているよう

<?php 
require '../src/facebook.php'; 

// Create our Application instance (replace this with your appId and secret). 
$facebook = new Facebook(array(
    'appId' => '137061043024243', 
    'secret' => '619c4dc94343584eb7792ae9933978c9', 
    'cookie' => true, 
)); 

// We may or may not have this data based on a $_GET or $_COOKIE based session. 
// 
// If we get a session here, it means we found a correctly signed session using 
// the Application Secret only Facebook and the Application know. We dont know 
// if it is still valid until we make an API call using the session. A session 
// can become invalid if it has already expired (should not be getting the 
// session back in this case) or if the user logged out of Facebook. 
$session = $facebook->getSession(); 

$me = null; 
// Session based API call. 
if ($session) { 
    try { 
    $uid = $facebook->getUser(); 
    $me = $facebook->api('/me'); 
    $friends = $facebook->api('/me/friends'); 
    } catch (FacebookApiException $e) { 
    error_log($e); 
    } 
} 

// login or logout url will be needed depending on current user state. 
if ($me) { 
    $logoutUrl = $facebook->getLogoutUrl(); 
} else { 
    $loginUrl = $facebook->getLoginUrl(); 
} 

// This call will always work since we are fetching public data. 
$naitik = $facebook->api('/naitik'); 

?> 
<!doctype html> 
<html xmlns:fb="http://www.facebook.com/2008/fbml"> 
    <head> 
    <title>php-sdk</title> 
    <style> 
     body { 
     font-family: 'Lucida Grande', Verdana, Arial, sans-serif; 
     } 
     h1 a { 
     text-decoration: none; 
     color: #3b5998; 
     } 
     h1 a:hover { 
     text-decoration: underline; 
     } 
    </style> 
    </head> 
    <body> 
    <!-- 
     We use the JS SDK to provide a richer user experience. For more info, 
     look here: http://github.com/facebook/connect-js 
    --> 
    <div id="fb-root"></div> 
    <script> 
     window.fbAsyncInit = function() { 
     FB.init({ 
      appId : '<?php echo $facebook->getAppId(); ?>', 
      session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it 
      status : true, // check login status 
      cookie : true, // enable cookies to allow the server to access the session 
      xfbml : true // parse XFBML 
     }); 


     // whenever the user logs in, we refresh the page 
     FB.Event.subscribe('auth.login', function() { 
      window.location.reload(); 
     }); 
     }; 

     (function() { 
     var e = document.createElement('script'); 
     e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
     e.async = true; 
     document.getElementById('fb-root').appendChild(e); 
     }()); 
    </script> 


    <?php if ($me): ?> 
    <a href="<?php echo $logoutUrl; ?>"> 
     <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif"> 
    </a> 
    <?php else: ?> 
    <div> 
     Using JavaScript &amp; XFBML: <fb:login-button></fb:login-button> 
    </div> 
    <div> 
     Without using JavaScript &amp; XFBML: 
     <a href="<?php echo $loginUrl; ?>"> 
     <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif"> 
     </a> 
    </div> 
    <?php endif ?> 
    <?php $array = array(); 
      $nr = count($friends['data']); 

      echo $nr; 

     for($i = 0; $i < $nr; $i++) { 
      $array[$i] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture"; 
     } 
     header('Content-type: application/json'); 
     echo json_encode($array); 
     ?> 
    </body> 
</html> 


JAVASCRIPT 

    $.post("getProfilePhotos.php", function(data) { alert(data); console.log(data);/*DO WHAT YOU WANT WITH DATA HERE*/}, "json"); 

window.onload = init; 
function init() { 
    if (window.Event) { 
     document.addEventListener("mousemove", getCursorXY("mousemove"), false); 
     var cursorXX = 0; 
     var cursorYY = 0; 

     var cursorX = document.getElementById("cursorX"); 
     var cursorY = document.getElementById("cursorY"); 

     cursorX.innerHTML = cursorXX; 
     cursorY.innerHTML = cursorYY; 
    } 

    //initializare canvas1 
    canvas = document.getElementById('game'); 
    //coordonatele unde se afla mouseul 
    canvas.onmousemove = getCursorXY; 

    //initializare canvas2 
    canvas2 = document.getElementById('teroristi'); 
    //coordonatele unde se afla mouseul 
    canvas2.onmousemove = getCursorXY; 

    //lista de inamici 
    lista = new Array(); 

    initial(); 

    for(var j = 0; j < 20; j++) 
     for(var k = 0; k < 2;k++) 
      console.log(matx[j][k]);// = -1000; 

    scor = 0; 
    viata = 5; 

    //creerea contextului de desenare 2D 
    ctx2 = canvas2.getContext("2d"); 
    ctx = canvas.getContext("2d"); 

    //creerea unui obiect imagine 
    img = new Image(); 
    img.src = 'glont.png'; 

    imgTerorist = new Image(); 
    imgTerorist.src = 'terorist.jpg'; 

    ctx.beginPath(); 
    ctx.stroke(); 

    imgviata = new Image(); 
    imgviata.src = 'vieti.png'; 
    //score(); 
    viataF(); 
} 

//initializeaza matricea de aparitii 
function initial(){ 

    matx = new Array(24); 
    for (var m = 0; m <24; m++) 
     matx[m] = new Array(3); 

    for(var m = 0; m < 24; m++) 
     matx[m][2] = 0; 

    matx[0][0] = 20; 
    matx[0][1] = 20; 

    for(var m = 1; m < 6; m++){ 
     matx[m][0] = matx[m-1][0] + 80; 
     matx[m][1] = matx[m-1][1]; 
    } 

    matx[6][0] = matx[0][0]; 
    matx[6][1] = matx[0][1] + 120; 

    for(var m = 7; m < 12; m++){ 
     matx[m][0] = matx[m-1][0] + 80; 
     matx[m][1] = matx[m-1][1]; 
    } 

    matx[12][0] = matx[0][0]; 
    matx[12][1] = matx[0][1] + 240; 

    for(var m = 13; m < 18; m++){ 
     matx[m][0] = matx[m-1][0] + 80; 
     matx[m][1] = matx[m-1][1]; 
    } 

    matx[18][0] = matx[0][0]; 
    matx[18][1] = matx[0][1] + 360; 

    for(var m = 19; m < 24; m++){ 
     matx[m][0] = matx[m-1][0] + 80; 
     matx[m][1] = matx[m-1][1]; 
    } 

} 

function getCursorXY(e) { 

    //se ia pozitia de pe axa x al cursorului 
    cursorXX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); 

    //se ia pozitia de pe axa y al cursorului 
    cursorYY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); 

    // 
    var cursorX = document.getElementById("cursorX"); 
    var cursorY = document.getElementById("cursorY"); 

    cursorX.innerHTML = cursorXX; 
    cursorY.innerHTML = cursorYY; 
} 

function Nr(){ 
    return Math.floor(Math.random()*24); 
} 

//stergerea inamicului 
function sterge(x){ 
    //setTimeout("genereaza(flag)",3000); 
    var img = ctx.createImageData(60, 100); 
    for (var i = img.data.length; --i >= 0;) 
     img.data[i] = 0; 
    ctx.putImageData(img, matx[x][0], matx[x][1]); 
    matx[x][2] = 0; 
} 

//genereaza inamici 
function genereaza(flag){ 
    if(flag == 1){ 
     setTimeout("genereaza(flag)", 2000); 
     var x = Nr(); 
     terorist(x); 
     if(lista.length > 3){ 
      viata = viata - 1; 
      sterge(lista[0]); 
      lista.splice(0, 1); 
      viataF(); 
     } 
    } 
} 

//creeaza un inamic 
function terorist(x){ 
    console.log("X primit = " + x + "valoarea flagului = " + matx[x][2]); 
    //sterge(x); 
    if(matx[x][2] == 0){ 
     ctx.drawImage(imgTerorist,matx[x][0],matx[x][1]); 
     matx[x][2] = 1; 
     lista.push(x); 
    } 
    else if(matx[x][2] == 1){ 

     var q = Nr(); 
     console.log("in recursie: " + q); 
     terorist(q); 
    } 
} 

function viataF(){ 
    var remove = ctx2.createImageData(20,20); 
    for (var i = remove.data.length; --i >= 0;) 
     remove.data[i] = 0; 
    ctx2.putImageData(remove, 10, (10+(viata*20))); 

    console.log(viata); 
    for(var m = 0; m < viata; m++) 
     ctx2.drawImage(imgviata,10,(10+(m*20))); 
} 

function impuscat(){ 

    var shootX = cursorXX; 
    var shootY = cursorYY; 
    var tm = 0; 

    console.log("ShootX = " + shootX + " ShootY = " + shootY); 

    for(var m = 0, tm = lista.length; m < tm; m++){ 
     if(shootX >= matx[lista[m]][0] && shootX <= matx[lista[m]][0] + 60 && shootY >= matx[lista[m]][1] && shootY <= matx[lista[m]][1] + 100){ 
      sterge(lista[m]); 
      lista.splice(m, 1); 
      scor = scor + 10; 
      console.log("IMPUSCAT"); 
     } 
    } 
} 

function glont(x, y){ 
    ctx.beginPath(); 
    ctx.stroke(); 
    ctx.drawImage(img,x-40,y-40); 
    impuscat(); 
} 

function mouse(){ 

    impuscat(); 
    /*console.log('Maus apasat'); 
    console.log(cursorXX); 
    console.log(cursorYY);*/ 
    //glont(cursorXX, cursorYY); 
    //console.log("Dupa glont()"); 
} 
function start(){ 
    viataF(); 
    flag = 1; 
    genereaza(flag); 
    setTimeout("stop()", 10000); 
} 

function stop(){ 
    ctx2.fillStyle = '#000000'; 
    ctx2.strokeStyle = '#FFFFFF'; 
    ctx2.font   = 'bold 30px sans-serif'; 
    ctx2.fillText ('TIMPUL A EXPIRAT!', 100, 200); 
    ctx2.fillText('Scorul tau este: ' + scor, 100, 235); 
    console.log("TIMPUL A EXPIRAT"); 
    flag = 0; 
    genereaza(flag); 
} 

function score(){ 
    ctx2.fillStyle = '#000000'; 
    ctx2.strokeStyle = '#FFFFFF'; 
    ctx2.font   = 'bold 15px sans-serif'; 
    ctx2.fillText('Scorul tau este: ', 350, 20); 
} 
+0

あなたの質問に関してもっと情報を共有したい場合は、質問を編集してください。以下の投稿は回答のみであり、更新ではありません。今回は複数の投稿を元の質問にマージします。ありがとうございました。 – Sampson

答えて

3

あなたのPHPセクションが間違っています。

また、ループ内の配列処理が正しくありません。

にPHPコードを変更してみてください:

<?php 
$friendData = array(); 

foreach ($friends['data'] as $cFriend) { 
    $friendData[$cFriend['id']] = "http://graph.facebook.com/" . $cFriend['id'] . "/picture"; 
} 

header('Content-Type: application/json'); 
echo json_encode($friendData); 
exit; 
0

することができますようにヘッダーが、この場合には動作しませんではないブラウザへの出力(空白を含む)任意のコンテンツを使用すると、ヘッダ(呼び出す前に)。あなたのforループでは、HTMLをブラウザに出力し、エラーを引き起こします。

Orblingは、要素を配列に正しく追加していないとも言っています。私は、これはあなたが望むものであると仮定していますが、あなたがしたいループがある:

for($i = 0; $i < $nr; $i++) { 
    $array[] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture"; 
} 

私はあなたのJavaScriptで達成しようとしているものによって混乱しています。私は簡単にするために代わりに次のコードを使用します。

$.post("getProfilePhotos.php", function(data) { alert(data); //DO WHAT YOU WANT WITH DATA HERE }, "json"); 

私はあなたがJSONを取り戻すと、あなたは戻っJSONでやりたいコールバック関数を用いて約遊ぶ確認するために最初にそのコードを実行します。

+0

コンソールでエラーが発生しました。これはエラーです。 [02:46:21.281]:/、 'ポスト' script.jsでhttp://romanager.ro/api/examples/script.js:3 ライン3 @プロパティリストの後に不足している}が タイプです/ postまたはgetメソッド 実際には、私はFacebookのプロフィール写真から取得したい。 PHPのスクリプトで私は写真を取得することができたが、私はPHPからjavascriptにIDを転送することができます。必要ならば私はPHPスクリプトとjavascriptファイル全体を書き込もうとします – Urmelinho

+0

はまだこれらのスクリプトに問題があります。私はfacebookでユーザーのIDを取得する必要があるため、彼の友達のIDを取得するためにPHPスクリプトでは、私はやFacebookのユーザーの認証を行います。ログインするにはPHPスクリプトでhtmlを作成する必要があります。私はスクリプトのコードを投稿し、あなたが私を助けてくれることを願っています。 – Urmelinho