我,每當我的形式被提交(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
我在做什麼錯?如何使用數組中值爲變量而不是硬編碼的值?
他沒有用'return' – taylorcressy 2014-09-25 17:00:37
它似乎並不像你解析響應? ''console.log' – taylorcressy 2014-09-25 17:01:40
@taylorcressy之前在''console.log'之前試着'JSON.parse',因爲OP使用jQuery的ajax方法並將'dataType'選項設置爲'json',它會自動將JSON文本解析爲javascript對象 – 2014-09-25 17:02:57