JQuery getJSON - ajax 解析错误

发布于 2024-07-15 00:28:25 字数 1856 浏览 10 评论 0原文

我尝试使用 JQuery getJSON 和 ajax 解析以下 json 响应:

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

我还尝试转义“/”字符,如下所示:

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

当我使用 getJSON 时,它不会执行回调。 因此,我使用 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);
    }
});

ajax 遇到错误并发出以下警报:

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

textStatus=parseerror

errorThrown=undefined

然后我尝试使用以下代码进行简单的 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");
})

.get 返回 JSON,但 eval 出现无论我如何修改 JSON(内容类型标头、格式的其他变体等),都会出现错误。

我发现返回 JSON 中的 HTML 并获取它似乎存在问题解析。 然而,我希望我可能错过了一些可以让我通过 JSON 获取这些数据的东西。 有人有什么想法吗?

I've tried to parse the following json response with both the JQuery getJSON and ajax:

[{"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. So, I tried it with JQuery ajax as follows:

$.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:

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:

$.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.)

What I've come up with is that there seem to be an issue returning the HTML in the JSON and getting it parsed. However, I have hope that I may have missed something that would allow me to get this data via JSON. Does anyone have any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

无敌元气妹 2024-07-22 00:28:25

您拥有的 JSON 字符串是一个数组,其中包含 1 个对象,因此要访问该对象,您必须首先访问该数组。 使用看起来像这样的 json.php:

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

我刚刚尝试过这个,

$.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"
});

我也尝试过这个:

$.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" 
});

他们都对我来说工作得很好。

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. With a json.php that looks like this:

[
    {
        "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.

想挽留 2024-07-22 00:28:25

您是否尝试过对 HTML 进行 XML 编码(即

)?

Did you try XML-encoding the HTML (i.e. <H1>)?

作妖 2024-07-22 00:28:25

您可以将其作为文本返回,然后使用 json.org 解析器
解析它
看看它的工作原理是否有什么不同

You could have it return as text and then parse it with the json.org parser
To see if it works any differently

第七度阳光i 2024-07-22 00:28:25

请注意,问题中存在语法错误。 的行

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

应为

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

This 也有很大的不同。

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.

清风不识月 2024-07-22 00:28:25

删除 JsonData 前面和最后的 [],它就可以工作了。

Remove the [], on front and last on JsonData, and it work.

冷︶言冷语的世界 2024-07-22 00:28:25

这是一个工作示例并经过测试!

<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>

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}]

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):

[{ "label": "Series1",  "data": 10},
{ "label": "Series2",  "data": 30},
{ "label": "Series3",  "data": 90},
{ "label": "Series4",  "data": 70},
{ "label": "Series5",  "data": 80},
{ "label": "Series6",  "data": 110}]
ㄖ落Θ余辉 2024-07-22 00:28:25

如果有人仍然遇到此问题,那是因为您的响应需要是 JSON 字符串和内容类型“application/json”。

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

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

hth、

Matti

If anyone is still having problems with this it's because your response needs to be a JSON string and content-type "application/json".

Example for HTTP in asp.net (c#):

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

hth,

Matti

满天都是小星星 2024-07-22 00:28:25

首先,尝试查明问题是否与一般 JSON 编码/解码有关。 尝试使用更简单的对象,使用数字和纯字符串,然后使用带引号的 HTML。

当你让 JSON 工作后,你真的应该考虑从那里删除 HTML。 更好的方法是仅移动数据,并将演示细节留给模板。 当使用 AJAX 时,这意味着 HTML 中隐藏模板,并使用 jQuery 复制它并填充数据。 检查任何 jQuery 模板插件。 其中,jTemplates 是最受欢迎的。

First, try to pinpoint if the problem is with general JSON encoding/decoding. try simpler objects, with numbers and plain strings, then with quoted HTML.

After you get JSON working, you really should really consider removing the HTML from there. 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. check any of the jQuery template plugins. Of these, jTemplates is a common favorite.

明媚如初 2024-07-22 00:28:25

可能是因为您的输出缓冲区不为空,所以 AJAX 接收到不属于 JSON 的字节。

在使用 echodie() 输出 json 之前,尝试在服务器端使用 ob_clean() 清理缓冲区。 而且您不需要指定 contentType,我认为默认值对您来说可以正常工作。

我有同样的问题并且它解决了。

希望对您有所帮助。

It is maybe because your output buffer is not empty, so AJAX receive bytes which don't belong to the JSON.

Try clean buffer with ob_clean() on server side just before output your json with echo or die(). And you don't need to specify contentType, I think for you default value will work correctly.

I had the same problem and it solve it.

Hope to help you.

清君侧 2024-07-22 00:28:25

昨天,$. ajax依然没有错误,今天是引用错误,有人说parsererror是jquery版本的问题,我用的是jquery-1.3.2.min.js,昨天的。 这个版本也完成了,今天就废了。 数据来源:无变化。 不知道是什么原因?

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. This edition also done, today is washed-up. Data sources: no change. Don't know what reason be?

从﹋此江山别 2024-07-22 00:28:25

我认为你问了错误的问题。 使用 $.getJSON() 更容易,如果您遇到问题,最好要求 $.getJSON() 而不是 $.ajax()。
您可能还会发现查看 getJSON 函数源代码很有用,因为我发现,您在 mimeTypes 中得到了很多无用的东西。 不是这样的。

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().
You might also find useful looking at getJSON function source code, because I see, you got a lot of useless stuff there with mimeTypes. That's not the way.

别闹i 2024-07-22 00:28:25

您尝试解析的值包含在方括号 [] 中,这意味着它是一个数组。 您正在尝试评估一个数组。 尝试评估数组的第一个元素,它应该可以工作...

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

另外,我建议使用提供的 JSON.parse() 这里而不是直接调用 eval() 。

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.

败给现实 2024-07-22 00:28:25

我收到了类似的错误。 我花了一段时间才发现 - 我几乎不知道自 PHP5.2 以来 PHP 就不再(原生)支持 JSON。 重要提醒...

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. Critical reminder...

青丝拂面 2024-07-22 00:28:25

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

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

Don't use an array box, and make sure you format your data properly:

{"account":{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}}
旧人哭 2024-07-22 00:28:25

就我而言,错误是由 json 中的 html 标签引起的。

不正确(解析器错误)

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

正确的

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

浏览器:IE7/IE8

in my case, the error was caused by a html tag in the json.

INCORRECT (parsererror)

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

CORRECT

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

BROWSER: IE7/IE8

微凉徒眸意 2024-07-22 00:28:25

也请尝试此操作

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

在我的情况下,服务器在“{”之前以未知字符响应,

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 '{'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文