2016-12-01 54 views
1

为什么我的JSON值没有被解析成一个对象?jquery:json请求输出

这是我的jQuery部分

$.ajax({ 
       url:'url.php', 
       type:'post', 
       data:{'players':playersDone, 'userID':userID, 'gameVariant':gameVariant, 'gameWeek':gameWeek,}, 
       success: function (res) {       
        console.log(res); 
        alert(res); 
        alert(res.idOfLastRow); 
        window.location.href = " summary.php?idOfLastEntry='"+res.idOfLastRow+"' "; 
       } 
      }); 

和我PHP看起来是这样的:

... 
... 
     '".$_POST['players']['fw3']."', 
     ".$_POST['players']['sub']."', 
     '', 
     '');"; 

    mysqli_query($connection, $queryInsertFinishedDraft); 
    $_POST['players']['idOfLastRow'] = $connection->insert_id; 

JSON数据

当我输出我收到的数据在一个警报响应,它看起来像这样

{"df1":"952","idOfLastRow":77} 

然而,当我试图进入的领域之一,我得到未定义

alert(res.idOfLastRow)是在你的Ajax调用 “未定义”

+1

错误响应内容类型。打印json之前,请发送正确的内容类型。 'header(“Content-Type:application/json”);' –

+0

多数民众赞成它!谢谢!!!! –

回答

0

你需要添加的数据类型JSON

  url:'url.php', 
      type:'post', 
      dataType: 'json', <--- 
      data:{'players':playersDone, 'userID':userID, 'gameVariant':gameVariant, 'gameWeek':gameWeek,}, 
      success: function (res) { 
+0

对不起,但这不是解决方案:( SOlution是,我忘了添加一个头!像标题(“内容类型:应用程序/ JSON”); –

0

您可以选择在PHP中返回正确的内容类型,并让jquery做到这一点:

header("Content-Type: application/json"); 

或解析字符串自己:

JSON.parse(res);