jquery 对 java后台换回的 json解析失败

ff上报错是:SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data

前端代码

 ChatMassage cm = ChatMassage.instance();
        String mas = cm.getMassage(num);
        int massageNumber = ChatMassage.mass_num;
        System.out.println("mnumber:"+massageNumber);
        session.setAttribute("massageNumber", massageNumber);
        JSONObject json = new JSONObject();
        json.put("massage", mas);
        json.put("massageNumber", massageNumber);
        System.out.println(json);

        return json;

前端问题

function loadMassage(){
    $.ajax({
        data: "num=" + massageNumber,
        url: "loadData.do",
        Success: $(function(msg){

            var res =$.parseJSON(msg);
            alert(parseInt(res.massageNumber));
            massageNumber=parseInt(res.massageNumber);
            massages+=res.massgae;
            document.body.innerHTML=massages;
        })
    });

json生成部分

 } else {
            cm.addUser(name);
            HttpSession session = request.getSession();
            session.setAttribute("username", name);
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            String data = dateFormat.format(new Date());
            cm.setMassage("<br><font color=\'red\'> welcom "+name+" join in chatting" + " at "+data+"</font><br>");
        }
 request header:
 Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8080/spring/chat
X-Requested-With: XMLHttpRequest
Cookie: JSESSIONID=26FBFB1DFC7729A3E1A423AECA8B2995
DNT: 1
Connection: keep-alive

Response Header:
Server: Apache-Coyote/1.1
Content-Type: : application/json
Content-Length: 108
Date: Mon, 25 Dec 2017 16:33:01 GMT

在返回时已设置编码

 Object result = action.execute(request, response);
        if(result instanceof String)
        {
            request.getRequestDispatcher(result.toString()).forward(request, response);
        } else if (result instanceof JSONObject) {
            response.setHeader("Content-Type:", "application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print((JSONObject)result);
        }

因为是 Linux 系统,所以一般情况下不会出现编码问题。并且我也将中文全部替换为英文。

之前在没开 debug 时,解析全部为 undefinded

解析全部为 undefinded

function loadMassage(){
var dataJson = JSON.stringify(json);
$.ajax({
data: dataJson,
url: "loadData.do",
Content-Type:"application/json",
dataType:'json',
type:"post",
Success: $(function(msg){

        var res =$.parseJSON(msg);
        alert(parseInt(res.massageNumber));
        massageNumber=parseInt(res.massageNumber);
        massages+=res.massgae;
        document.body.innerHTML=massages;
    })
});

试试类似这样的代码

```function loadMassage(){
$.ajax({
data: {num: massageNumber},//1
url: "loadData.do",
dataType: "json",
type:"get",//or "post"
error:function(resp){console.log(resp)},
success: function(msg){//3
console.log(msg);//2
//var res =$.parseJSON(msg);
//alert(parseInt(res.massageNumber));
//massageNumber=parseInt(res.massageNumber);
//massages+=res.massgae;
//document.body.innerHTML=massages;
}//4
});
}


如果你ajax请求返回的是json格式, 不需要parseJSON, 直接用就好, 如

msg.messageNumber
    msg.messages
    ......

https://www.cnblogs.com/zhaopengcheng/p/6890282.html

ajax 请求 对json传的处理 Jquery 使用Ajax获取后台返回的Json数据后,页面处理

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">









<br><br> $(function () {<br><br> $.ajax({<br><br> url: &#39;jsondata.ashx&#39;,<br><br> type: &#39;GET&#39;,<br><br> dataType: &#39;json&#39;,<br><br> timeout: 1000,<br><br> cache: false,<br><br> beforeSend: LoadFunction, //加载执行方法<br><br> error: erryFunction, //错误执行方法<br><br> success: succFunction //成功执行方法<br><br> })<br><br> function LoadFunction() {<br><br> $(&quot;#list&quot;).html(&#39;加载中...&#39;);<br><br> }<br><br> function erryFunction() {<br><br> alert(&quot;error&quot;);<br><br> }<br><br> function succFunction(tt) {<br><br> $(&quot;#list&quot;).html(&#39;&#39;); </p> <pre><code> //eval将字符串转成对象数组 //var json = { &quot;id&quot;: &quot;10086&quot;, &quot;uname&quot;: &quot;zhangsan&quot;, &quot;email&quot;: &quot;zhangsan@qq.com&quot; }; //json = eval(json); //alert(&quot;===json:id=&quot; + json.id + &quot;,uname=&quot; + json.uname + &quot;,email=&quot; + json.email); var json = eval(tt); //数组 $.each(json, function (index, item) { //循环获取数据 var name = json[index].Name; var idnumber = json[index].IdNumber; var sex = json[index].Sex; $(&quot;#list&quot;).html($(&quot;#list&quot;).html() + &quot;&lt;br&gt;&quot; + name + &quot; - &quot; + idnumber + &quot; - &quot; + sex + &quot;&lt;br/&gt;&quot;); }); } }); &lt;/script&gt; </code></pre> <p></head><br><br> <body><br><br> <ul id="list"><br><br> </ul><br><br> </body><br><br> </html> </p> <p>[csharp] view plain copy print?在CODE上查看代码片派生到我的代码片<br> &lt;%@ WebHandler Language=&quot;C#&quot; Class=&quot;jsondata&quot; %&gt; </p> <p>using System;<br><br> using System.Web;<br><br> using System.Web.Script.Serialization;<br><br> using System.IO;<br><br> using System.Text;<br><br> using System.Collections.Generic;<br><br> using Newtonsoft.Json;<br><br> using System.Data; </p> <p>public class jsondata : IHttpHandler { </p> <pre><code>public void ProcessRequest(HttpContext context) { context.Response.ContentType = &quot;text/plain&quot;; string JsonStr = JsonConvert.SerializeObject(CreateDT()); context.Response.Write(JsonStr); context.Response.End(); } #region 创建测试数据源 //创建DataTable protected DataTable CreateDT() { DataTable tblDatas = new DataTable(&quot;Datas&quot;); //序号列 //tblDatas.Columns.Add(&quot;ID&quot;, Type.GetType(&quot;System.Int32&quot;)); //tblDatas.Columns[0].AutoIncrement = true; //tblDatas.Columns[0].AutoIncrementSeed = 1; //tblDatas.Columns[0].AutoIncrementStep = 1; //数据列 tblDatas.Columns.Add(&quot;IdNumber&quot;, Type.GetType(&quot;System.String&quot;)); tblDatas.Columns.Add(&quot;Name&quot;, Type.GetType(&quot;System.String&quot;)); tblDatas.Columns.Add(&quot;BirthDate&quot;, Type.GetType(&quot;System.String&quot;)); tblDatas.Columns.Add(&quot;Sex&quot;, Type.GetType(&quot;System.String&quot;)); tblDatas.Columns.Add(&quot;Wage&quot;, Type.GetType(&quot;System.Decimal&quot;)); tblDatas.Columns.Add(&quot;Bonus&quot;, Type.GetType(&quot;System.Decimal&quot;)); //统计列开始 tblDatas.Columns.Add(&quot;NeedPay&quot;, Type.GetType(&quot;System.String&quot;), &quot;Wage+Bonus&quot;); //统计列结束 tblDatas.Columns.Add(&quot;Address&quot;, Type.GetType(&quot;System.String&quot;)); tblDatas.Columns.Add(&quot;PostCode&quot;, Type.GetType(&quot;System.String&quot;)); //设置身份证号码为主键 tblDatas.PrimaryKey = new DataColumn[] { tblDatas.Columns[&quot;IdNumber&quot;] }; tblDatas.Rows.Add(new object[] { &quot;43100000000000&quot;, &quot;张三&quot;, &quot;1982&quot;, &quot;0&quot;, 3000, 1000, null, &quot;深圳市&quot;, &quot;518000&quot; }); tblDatas.Rows.Add(new object[] { &quot;43100000000001&quot;, &quot;李四&quot;, &quot;1983&quot;, &quot;1&quot;, 3500, 1200, null, &quot;深圳市&quot;, &quot;518000&quot; }); tblDatas.Rows.Add(new object[] { &quot;43100000000002&quot;, &quot;王五&quot;, &quot;1984&quot;, &quot;1&quot;, 4000, 1300, null, &quot;深圳市&quot;, &quot;518000&quot; }); tblDatas.Rows.Add(new object[] { &quot;43100000000003&quot;, &quot;赵六&quot;, &quot;1985&quot;, &quot;0&quot;, 5000, 1400, null, &quot;深圳市&quot;, &quot;518000&quot; }); tblDatas.Rows.Add(new object[] { &quot;43100000000004&quot;, &quot;牛七&quot;, &quot;1986&quot;, &quot;1&quot;, 6000, 1500, null, &quot;深圳市&quot;, &quot;518000&quot; }); return tblDatas; } #endregion public bool IsReusable { get { return false; } } </code></pre> <p>} </p> <p>[javascript] view plain copy print?在CODE上查看代码片派生到我的代码片</p> <!-- <script type="text/javascript"> $(function () { $.ajax({ url: 'jsondata.ashx', type: 'GET', dataType: 'json', timeout: 1000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { $("#list").html('加载中...'); } function erryFunction() { alert("error"); } function succFunction(tt) { $("#list").html(''); //eval将字符串转成对象数组 //var json = { "id": "10086", "uname": "zhangsan", "email": "zhangsan@qq.com" }; //json = eval(json); //alert("===json:id=" + json.id + ",uname=" + json.uname + ",email=" + json.email); var json = eval(tt); //数组 $.each(json, function (index, item) { //循环获取数据 var Key = json[index].key; var Info = json[index].info; // var idnumber = json[index].IdNumber; // var sex = json[index].Sex; $("#list").html($("#list").html() + "<br>" + Key + "----" + Info.name); //+ " - " + idnumber + " - " + sex + "<br/>"); }); } }); -->

[csharp] view plain copy print?在CODE上查看代码片派生到我的代码片
<%@ WebHandler Language="C#" Class="jsondata" %>

using System;

using System.Web;

using System.Web.Script.Serialization;

using System.IO;

using System.Text;

using System.Collections;

using System.Collections.Generic;

using System.Data;

public class jsondata : IHttpHandler {

public void ProcessRequest(HttpContext context)  
{  
    context.Response.ContentType = "text/plain";  
    context.Response.Cache.SetNoStore();  
    string data = "[{\"key\":\"1\",\"info\":{\"name\":\"222\",\"age\":\"333\",\"sex\":\"444\"}},{\"key\":\"2\",\"info\":{\"name\":\"999\",\"age\":\"000\",\"sex\":\"111\"}}]";  
    context.Response.Write(new JavaScriptSerializer().Serialize(data));  
}  


public bool IsReusable  
{  
    get  
    {  
        return false;  
    }  
}  

}

[html] view plain copy print?在CODE上查看代码片派生到我的代码片
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test2013.aspx.cs" Inherits="Test2013" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">









<br><br> function GetPara(o) {<br><br> var sortid = $(o).val();<br><br> $.ajax({<br><br> url: &#39;GetPara.ashx?type=get&amp;sortid=&#39; + sortid,<br><br> type: &#39;GET&#39;,<br><br> dataType: &#39;json&#39;,<br><br> timeout: 3000,<br><br> cache: false,<br><br> beforeSend: LoadFunction, //加载执行方法<br><br> error: erryFunction, //错误执行方法<br><br> success: succFunction //成功执行方法<br><br> })<br><br> function LoadFunction() {<br><br> $(&quot;#list&quot;).html(&#39;加载中...&#39;);<br><br> }<br><br> function erryFunction() {<br><br> alert(&quot;error&quot;);<br><br> }<br><br> function succFunction(tt) {<br><br> $(&quot;#list&quot;).html(&#39;&#39;);<br><br> var json = eval(tt); //数组<br><br> $.each(json, function (index, item) {<br><br> //循环获取数据<br><br> var Id = json[index].id;<br><br> var Name = json[index].name;<br><br> $(&quot;#list&quot;).html($(&quot;#list&quot;).html() + &quot;<br>&quot; + Name + &quot;<input type='text' id='" + Id + "' /><br/>&quot;);<br><br> });<br><br> }<br><br> }; </p> <pre><code> function SavePara() { var parameter = {}; $(&quot;#list input:text&quot;).each(function () { var key = $(this).attr(&quot;id&quot;); var value = $(this).val(); parameter[key] = value; }); $.ajax({ url: &#39;GetPara.ashx?type=save&#39;, type: &#39;POST&#39;, dataType: &#39;json&#39;, data: parameter, timeout: 3000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { } function erryFunction() { } function succFunction(tt) { } }; </code></pre> <p>











/asp:DropDownList

        <input type="button" value="保存数据" onclick="SavePara()" />  
    </div>  
    </form>  
    



    [csharp] view plain copy print?在CODE上查看代码片派生到我的代码片
    <%@ WebHandler Language="C#" Class="GetPara" %>

    using System;

    using System.Web;

    using System.Data;

    using System.Collections.Generic;

    using System.Web.Script.Serialization;

    public class GetPara : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

    context.Response.ContentType = "text/plain";

    string SortId = context.Request["sortid"];

    string Type = context.Request["type"];

    if (Type=="get")

    {

    if (!string.IsNullOrEmpty(SortId))

    {

    DataTable dt = MSCL.SqlHelper.GetDataTable("select * from PR_PRODUCTPARAS where sortid='" + SortId + "' ");

    List list = new List();

    for (int i = 0; i < dt.Rows.Count; i++)

    {

    Paras a = new Paras();

    a.id = dt.Rows[i]["PARAID"].ToString();

    a.name = dt.Rows[i]["PARANAME"].ToString();

    list.Add(a);

    }

    context.Response.Write(new JavaScriptSerializer().Serialize(list));

    }

    }

    else if (Type == "save")

    {

    //反序列化json

    System.IO.Stream stream = context.Request.InputStream;

    System.IO.StreamReader sr = new System.IO.StreamReader(stream, System.Text.Encoding.GetEncoding("UTF-8"));

    string sJson = sr.ReadToEnd();

    if (sJson.Contains("&"))

    {

    string[] sArr = sJson.Split('&');

    for (int i = 0; i < sArr.Length; i++)

    {

    string[] sArr1 = sArr[i].Split('=');

    object id = sArr1[0];

    object value = sArr1[1];

    }

    }

    }

    else

    { }

    }

    public bool IsReusable {  
        get {  
            return false;  
        }  
    }  
    
    public struct Paras  
    {  
        public string id;  
        public string name;   
    }  
    

    }

    dataType: "json",

    和dataType: "json"没关系,写不写都无所谓,我以前也遇到这个问题了,你只需要把这个JSONObject json = new JSONObject();替换掉,用一个json的生成包,调用里面的方法来进行json转换就好了,具体的包你可以百度一下,我现在没有电脑,不能发

    上述所说的几个包,使用里面的json转义应该就好了

    commons-beanutils-1.8.3.jar
    commons-collections-3.2.jar
    commons-lang.jar
    commons-logging-1.1.jar
    ezmorph-1.0.jar
    json-lib-2.2.2-jdk15.jar

    你可以去 http://www.manyjar.com/ 下载,里面的架包应该都有,而且免费,很实用的一个架包网站

    提供给你两个解决方案:
    一:后台直接传输Map。在前台接收到以后就是一个Object对象。可以通过data.key,获取value;
    二:使用console.log(data);查看前端接收到的data是什么格式。根据data的格式,获取你所需要的内容。

    看结果是返回值不少json格式的值导致的,可能原因:后台处理返回值错误或者前台解析函数有问题,具体问题具体分析,debugger一下,看data值有没有值,在console使用函数解析下,问题应该很快就会出现。
    另,总感觉你ajax写的有问题,但是不知道具体代码不能确定

    已经是json 为什么还要解析成json ?

    你不是设置这个了么 ?
    response.setHeader("Content-Type:", "application/json");

    后台方法不能直接返回JSON对象,需要做以下处理。

    //调用
    JSONObject json = new JSONObject();
    json.put("status", "SUCCESS");
    
    ajax(json.toString());
    
        /**
        * JSON格式输出
        */
    public String ajax(String jsonStr) {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/plain;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(jsonStr);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    

    ```function loadMassage(){
    $.ajax({
    data: {num: massageNumber},//1
    url: "loadData.do",
    dataType: "json",
    type:"get",//or "post"
    error:function(resp){console.log(resp)},
    success: function(msg){//3
    console.log(msg);//2
    //var res =$.parseJSON(msg);
    //alert(parseInt(res.massageNumber));
    //massageNumber=parseInt(res.massageNumber);
    //massages+=res.massgae;
    //document.body.innerHTML=massages;
    }//4
    });
    }

    我只知道json依赖包 responsebody ajax异步请求

    直接传输过来的数据就是json格式
    用$('')使用就好了

    JSON.stringify(a); 试试这个函数吧json对象转为字符串

    1.首先ajax中没有限制返回类型必须是
    type:‘json’
    2.返回数据类型不是json格式,需要解析为json格式使用:
    $.parseJSON(msg);
    否则直接使用即可