鍍金池/ 問答/Java  HTML/ JSON和解析問題

JSON和解析問題

后臺(tái)返回json結(jié)果的邏輯是

    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("userType", userType);
    resultMap.put("phone", phone);
    resultMap.put("channel", channel);
    JSONObject obj = new JSONObject();
    obj.put("code", "2000");
    obj.put("message", "成功");
    obj.put("result", resultMap);
    return obj.toJSONString();
 

前臺(tái)得到:

{"code":"2000","message":"成功","result":{"phone":"15365166305","channel":"null","userType":"高級(jí)版用戶"}}

可是在ajax里出現(xiàn)解析錯(cuò)誤,怎么辦?

           success: function(data){
                if(data.code == '2000'){
                    userType = data.result.userType;
                }
            },
            error: function(request, textStatus, errorThrown){
                console.log(request.status);
                console.log(request.readyState);
            }   
                

errorThrown說是:

Unexpected token < in JSON at position 0"
回答
編輯回答
風(fēng)畔

先確認(rèn)一下 content-type 吧,response 的 content-type 是 json 么?看報(bào)錯(cuò)不太像,很像是返回了 text/html 的 header

2018年5月22日 00:27
編輯回答
你的瞳

實(shí)際上前臺(tái)得到的肯定不是你貼的那一串 JSON 字符串, 你需要在瀏覽器network 欄下面找到指定請(qǐng)求的響應(yīng)來確認(rèn),并不是看到一個(gè) 頁面里面是這個(gè)就完了。

有可能的結(jié)果類似:

<html>
<body>
{"code":"2000","message":"成功","result":{"phone":"15365166305","channel":"null","userType":"高級(jí)版用戶"}}
</body>
</html>
2018年2月3日 22:37
編輯回答
青檸

看起來像是中文問題。前后臺(tái)編碼一致嗎?

2017年8月11日 17:07
編輯回答
尤禮

返回來的是json字符串,需要處理一下

 success: function(data) {
      var data = JSON.parse(data)
      if (data.code == '2000') {
        userType = data.result.userType;
      }
    }
2017年12月17日 08:00