2014-09-23 122 views
0

我有一個ajax後,看起來像這樣:(位於:post.phpAJAX/PHP - 獲取特定數據從回來後(通過數據)

$.ajax({ 
       type: "POST", 
       url: 'prize.php', 
       cache: false, 
       beforeSend: function(req) { 
        req.setRequestHeader("Accept", 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'); 
       }, 
       data: {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, textStatus, xhr) { 

       if(data=="success"){ 

         $('#status').text("You won: $<?php echo $data['prize'] ?>!"); 


       }else { 
        $("#m_error_msg").html(data); 
       } 


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

上述AJAX調用,帖此頁: prize.php,看起來像這樣:

if($_POST){ 
    $data = array("data"=>"success","code"=>"100","prize"=>"$prize","type"=>"$text"); 
    die($data['data']); 
} 

我的問題是..我怎樣才能通過$data['prize']$data['type']到:

if(data=="success"){} 

代碼?

回答

2

添加dataType:'json'$.ajax()處理程序申報您希望從服務器接收json encoded結果返回:

type: "POST", 
url: 'prize.php', 
cache: false, 
dataType:'json', 

然後從服務器您的回覆,發回一個json_encoded版陣列。

echo json_encode($data); 
die(); 

然後在你的成功的功能,讓我們檢查:

success: function(data){ 
    if(data.data == 'success'){ 

    } 
}