简体   繁体   English

JQuery getJSON - ajax parseerror

[英]JQuery getJSON - ajax parseerror

I've tried to parse the following json response with both the JQuery getJSON and ajax: 我试图用JQuery getJSON和ajax解析以下json响应:

[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}]

I've also tried it escaping the "/" characters like this: 我也试过它像这样转义“/”字符:

[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview <\/h1><h1>January 29, 2009<\/h1>"}]

When I use the getJSON it dose not execute the callback. 当我使用getJSON时,它不会执行回调。 So, I tried it with JQuery ajax as follows: 所以,我用JQuery ajax尝试了如下:

$.ajax({
    url: jURL,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/j-son;charset=UTF-8");
        }
    },
    success: function(data){
        wId = data.iId;
        $("#txtHeading").val(data.heading);
        $("#txtBody").val(data.body);
        $("#add").slideUp("slow");
        $("#edit").slideDown("slow");
    },//success
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
    }
});

The ajax hits the error ans alerts the following: ajax命中错误并警告以下内容:

XMLHttpRequest=[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview </h1><h1>January 29, 2009</h1>"}]

textStatus=parseerror

errorThrown=undefined

Then I tried a simple JQuery get call to return the JSON using the following code: 然后我尝试了一个简单的JQuery get调用,使用以下代码返回JSON:

$.get(jURL,function(data){
    var json = eval("("+data+");");
    wId = json.iId;
    $("#txtHeading").val(json.heading);
    $("#txtBody").val(json.body);
    $("#add").slideUp("slow");
    $("#edit").slideDown("slow");
})

The .get returns the JSON, but the eval comes up with errors no matter how I've modified the JSON (content-type header, other variations of the format, etc.) .get返回JSON,但无论我如何修改JSON(内容类型标题,格式的其他变体等),eval都会出现错误。

What I've come up with is that there seem to be an issue returning the HTML in the JSON and getting it parsed. 我想到的是,在JSON中返回HTML并解析它似乎存在问题。 However, I have hope that I may have missed something that would allow me to get this data via JSON. 但是,我希望我可能错过了一些允许我通过JSON获取此数据的内容。 Does anyone have any ideas? 有没有人有任何想法?

The JSON string you have is an array with 1 object inside of it, so to access the object you have to access the array first. 您拥有的JSON字符串是一个内部有1个对象的数组,因此要访问该对象,您必须首先访问该数组。 With a json.php that looks like this: 使用看起来像这样的json.php:

[
    {
        "iId": "1",
        "heading": "Management Services",
        "body": "<h1>Program Overview</h1><h1>January 29, 2009</h1>"
    }
]

I just tried this 我刚试过这个

$.getJSON("json.php", function(json) {
    alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
    alert(json[0].heading); // "Management Services"
    alert(json[0].iId); // "1"
});

I also tried this: 我也试过这个:

$.get("json.php", function(data){
    json = eval(data);
    alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
    alert(json[0].heading); // "Management Services"
    alert(json[0].iId); // "1" 
});

And they both worked fine for me. 他们都对我很好。

If anyone is still having problems with this it's because your response needs to be a JSON string and content-type "application/json". 如果有人仍然遇到问题,那是因为你的响应需要是一个JSON字符串和内容类型“application / json”。

Example for HTTP in asp.net (c#): asp.net(c#)中的HTTP示例:

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.Write("{ status: 'success' }");
    }

hth, 心连心,

Matti 马蒂

This is a working example and tested! 这是一个有效的例子并经过测试!

<script type="text/javascript">

function fetchData() {
var dataurl = "pie.json";
$.ajax({
    url: dataurl,
    cache: false,
    method: 'GET',
    dataType: 'json',
    success:  function(series) {
        var data = [];
        //alert(series.length);
        for (var i=0; i<series.length;i++){
            data[i]=series[i];
        }

        $.plot(
                $("#placeholder"), 
                data, 
                {
                     series: {
                       pie: {
                         show: true,
                         label: {
                           show: true
                         }
                     }
                    },
                    legend: {
                      show: true
                    }
                  }
       );
     }
});

   //setTimeout(fetchData, 1000);
}
</script>

And the json source is the following (pie.json): json源代码如下(pie.json):

[{ "label": "Series1",  "data": 10},
{ "label": "Series2",  "data": 30},
{ "label": "Series3",  "data": 90},
{ "label": "Series4",  "data": 70},
{ "label": "Series5",  "data": 80},
{ "label": "Series6",  "data": 110}]

Pleas note that in the question there is a syntax error. 请注意,在问题中存在语法错误。 The line with 这条线

x.overrideMimeType("application/j-son;charset=UTF-8");

should read 应该读

x.overrideMimeType("application/json; charset=UTF-8");

This makes a big difference too. 这也有很大的不同。

删除JsonData上前面和后面的[],它可以正常工作。

Disabling Firebug Lite fixed this problem for me. 禁用Firebug Lite为我解决了这个问题。

Bug with combination of: jQuery 1.4, ajax/json, Firebug Lite and IE 8 组合的错误:jQuery 1.4,ajax / json,Firebug Lite和IE 8

您是否尝试过对HTML进行XML编码(即&lt; H1&gt;)?

You could have it return as text and then parse it with the json.org parser 您可以将其作为文本返回,然后使用json.org解析器进行解析
To see if it works any differently 看它是否有所不同

also try this 也尝试这个

$.ajax({
    url: url,
    data:datas,
    success:function(datas, textStatus, jqXHR){
    var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));
})};

in my case server responds with unknow character before '{' 在我的情况下,服务器在'{'之前以未知字符响应

不要使用数组框,并确保正确格式化数据:

{"account":{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}}

I received a similar error. 我收到了类似的错误。 Took me a while to find out - little did I know that PHP has not (natively) supported JSON since PHP5.2. 花了一些时间才发现 - 我很少知道PHP自PHP5.2起就没有(本机地)支持JSON。 Critical reminder... 关键提醒......

Yesterday at $. 昨天在$。 Ajax still no mistakes, today is quoted the mistake, some say parsererror jquery version of the problem, what I use is jquery-1.3.2.min.js, yesterday. Ajax仍然没有错误,今天引用了错误,有人说parsererror jquery版本的问题,我用的是jquery-1.3.2.min.js,昨天。 This edition also done, today is washed-up. 这个版本也完成了,今天就被淘汰了。 Data sources: no change. 数据来源:没有变化。 Don't know what reason be? 不知道是什么原因?

It is maybe because your output buffer is not empty, so AJAX receive bytes which don't belong to the JSON. 这可能是因为您的输出缓冲区不为空,因此AJAX接收不属于JSON的字节。

Try clean buffer with ob_clean() on server side just before output your json with echo or die() . 在使用echodie()输出json之前,尝试使用服务器端的ob_clean()清理缓冲区。 And you don't need to specify contentType , I think for you default value will work correctly. 而且您不需要指定contentType ,我认为您的默认值将正常工作。

I had the same problem and it solve it. 我有同样的问题,它解决了它。

Hope to help you. 希望能帮到你。

First, try to pinpoint if the problem is with general JSON encoding/decoding. 首先,尝试确定问题是否与一般JSON编码/解码有关。 try simpler objects, with numbers and plain strings, then with quoted HTML. 尝试使用数字和普通字符串的简单对象,然后使用带引号的HTML。

After you get JSON working, you really should really consider removing the HTML from there. 在让JSON工作之后,你真的应该考虑从那里删除HTML。 Much better is to move just data, and leave presentation details to the templates. 更好的方法是移动数据,并将演示文稿详细信息留给模板。 When using AJAX, that means a hidden template in the HTML, and use jQuery to replicate it and fill with the data. 使用AJAX时,这意味着HTML中的隐藏模板,并使用jQuery复制它并填充数据。 check any of the jQuery template plugins . 检查任何jQuery 模板插件 Of these, jTemplates is a common favorite. 其中, jTemplates是最受欢迎的。

I think you are asking wrong question. 我想你问的是错误的问题。 Using $.getJSON() is much easier, and if you got problem with it, would be better to ask for $.getJSON() than for $.ajax(). 使用$ .getJSON()要容易得多,如果你遇到问题,最好还是要求$ .getJSON()而不是$ .ajax()。 You might also find useful looking at getJSON function source code, because I see, you got a lot of useless stuff there with mimeTypes. 您可能还会发现有用的getJSON函数源代码,因为我看到,你在mimeTypes中有很多无用的东西。 That's not the way. 那不是那样的。

The value you are trying to parse is wrapped in brackets [], which means it is an array. 您尝试解析的值包含在方括号[]中,这意味着它是一个数组。 You are trying to eval an array. 您正在尝试评估数组。 Try to eval the first element of the array, and it should work... 尝试评估数组的第一个元素,它应该工作...

var json = eval("("+data[0]+");");

Also, I would recommend using the JSON.parse() provided here instead of calling eval() directly. 另外,我建议使用此处提供的JSON.parse()而不是直接调用eval()。

in my case, the error was caused by a html tag in the json. 在我的情况下,错误是由json中的html标记引起的。

INCORRECT (parsererror) INCORRECT(parsererror)

{"msg": "Gracias,< br >Nos pondremos en contacto."}

CORRECT 正确

{"msg": "Gracias, nos pondremos en contacto."}

BROWSER: IE7/IE8 浏览器:IE7 / IE8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM