2014-09-25 98 views
0

我,每當我的形式被提交(post.php)運行以下功能:PHP - 返回數組jQuery的

$.ajax({ 
       type: "POST", 
       url: 'prize.php', 
       cache: false, 
       dataType:'json', 
       beforeSend: function(req) { 
        req.setRequestHeader("Accept", 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'); 
       }, 
       data: { stime: stime, key: key, aa: vAd , sw: screen.width, sh: screen.height, saw:screen.availWidth, sah: screen.availHeight, scd: screen.colorDepth, tz: (new Date().getTimezoneOffset()), bp: sbp, hf: have_flash}, 
       success: function(data){ 
       if(data.data == 'success'){ 
        console.log(data.text); 
       }else { 
        alert("error"); 
       } 


       }, 
       error: function(){ 
       } 
       }); 

prize.php看起來是這樣的:

if($_POST) 
{ 
    $validate = $wheel->validate(); 

    $error = ''; 
    $stop = false; 

    switch($validate) 
    { 
      case 1: 
       $error = 'You\'re not logged in..'; 
       $stop = true; 
      break; 
    } 

     //If no error = success.  
     if($validate['code'] == "100"){ 
      $won = $validate['prize']; 
      $type = $validate['type']; 
      $data = array("data"=>"success","code"=>"100","prize"=>"$prize","type"=>"$type"); 
      echo json_encode($data); 
      die(); 
     } 

     die($error); 

} 

現在,wheel.php (validate() function)將返回該:

$text = "dollar"; 
$prize = "50"; 
return array("data"=>"success","code"=>"100","prize"=>"$prize","type"=>"$text"); 

我的問題是,我不能使用「prize 「也不是」 type「從上面的陣列中,當I:

console.log(data.prize); 

它返回 」未定義「。

雖然,如果我做的一樣:console.log(data.code);它返回100

我在做什麼錯?如何使用數組中值爲變量而不是硬編碼的值?

+1

他沒有用'return' – taylorcressy 2014-09-25 17:00:37

+0

它似乎並不像你解析響應? ''console.log' – taylorcressy 2014-09-25 17:01:40

+1

@taylorcressy之前在''console.log'之前試着'JSON.parse',因爲OP使用jQuery的ajax方法並將'dataType'選項設置爲'json',它會自動將JSON文本解析爲javascript對象 – 2014-09-25 17:02:57

回答

1

$prize變量apperently不存在將其更改爲$won

if($_POST) 
{ 
    $validate = $wheel->validate(); 

    $error = ''; 
    $stop = false; 

    switch($validate) 
    { 
      case 1: 
       $error = 'You\'re not logged in..'; 
       $stop = true; 
      break; 
    } 

     //If no error = success.  
     if($validate['code'] == "100"){ 
      $won = $validate['prize']; 
      $type = $validate['type']; 
      $data = array("data"=>"success","code"=>"100","prize"=>"$won","type"=>"$type"); // $prize to $won 
      echo json_encode($data); 
      die(); 
     } 

     die($error); 

} 
+0

它返回:「undefined」..如在OP – oliverbj 2014-09-25 16:59:59

+0

@oliverbj說在OP哪裏說? Isaac正在談論PHP,而不是JavaScript。 – showdev 2014-09-25 17:08:01

+0

@showdev對不起,我編輯了我的答案,因爲這就是爲什麼oliverbj談OP:/ – Isaac 2014-09-25 17:09:15