2014-01-29 24 views
1

login.php上點擊按鈕我執行redirect.php。 這個redirect.php執行twitter身份驗證。爲此,它調用一些其他文件,然後調用index.php處理嵌套文件在php中包含並返回值到javascript函數

index.php給出結果nameid,我想在index.php中檢索。

源代碼:Git source code

目前發生的事情,從login.php中響應login.php和警報indefined value

的login.php

<body> 
      <input type="button" value="Run somePHPfile.php" id = "b1" /> 
    <script>  
    $('#b1').click(function() { 
     window.location.href = 'redirect.php';  

//This function needs improvement i think, is this correct place for this to get json value from index.php?? 
    $.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed 
     // data.id is the id 
      var id= data.id; 
      var name = data.name; 
      alert(name); 
      }); 
    }); 
    </script> 
    </body> 

redirect.php

<?php 

/* Start session and load library. */ 
session_start(); 
require_once('twitteroauth/twitteroauth.php'); 
require_once('config.php'); 

... //some other processing 
?> 
之前執行 $.get()

的index.php

<?php 
    session_start(); 
    require_once('twitteroauth/twitteroauth.php'); 
    require_once('config.php'); 

    if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) { 
     header('Location: ./clearsessions.php'); 
    } 
    $access_token = $_SESSION['access_token']; 
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); 
    $content = $connection->get('account/verify_credentials'); 
    $twitteruser = $content->{'screen_name'}; 
    $notweets = 5; 
    $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets); 

     $name = $content->{'name'}; 
    $id = $content->{'id'}; 
echo json_encode((object) array('id' => $id, 'name' => $name)); //to retreive in login.php 
?> 

UPDATE

$獲得( '的index.php',函數(數據){ VAR USER_ID = data.id; var name = data.name; alert(name); // alert(name); window.location.href ='button.php';

},「json」);

回答

2

,因爲你的PHP文件輸出你的get調用需要知道它是retriving一個JSON字符串,

$.get('index.php', function(data) { 
    var id= data.id; 
    var name = data.name; 
    alert(name); 
},"json"); 

這將讓jQuery的知道,它需要分析傳入的數據作爲JSON字符串和解析它到一個對象,否則你將不得不自己解析

$.get('index.php', function(data) { 
    data = JSON.parse(data); 
    var id= data.id; 
    var name = data.name; 
    alert(name); 
}); 
+0

謝謝,我在login.php中成功接收值。但請參閱index.php。它的瀏覽器不會回到'login.php'。它停在'index.php'上,並在屏幕上顯示'{「id」:200582436,「name」:「Karimkhan」}' –

+0

我想像'login.php - > redirect.php - > index.php(echo json值) - > login.php(移回主頁面)''。目前它是'login.php - > redirect.php - > index.php' –

+0

如果我使用'header(「location:../../ login.php」);'然後'login.php'能夠retreive name和id?即使在我使用它之後,它也不會重定向到登錄頁面 –