jQuery AJAX无法使用JSON响应

时间:2021-10-09 07:42:46

I have a JSON response from my php file like:

我有一个来自我的php文件的JSON响应,如:

[
  {"id":"1"},
  {"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]

And try to fetch this response into a div after button was clicked, however firebug is telling me the message from the error-handler. I can't figure out the problem?

并且在单击按钮后尝试将此响应提取到div中,但是firebug告诉我来自错误处理程序的消息。我无法弄清楚这个问题?

$('#loadarchive').click(function(){
    $.ajax({
        type: 'post',
        url: '/src/php/LoadAdminDashboardArchive.php',
        dataType: 'json',
        data: {
            action : 'getArchive'
        },
        success: function(results) {
            var archiveelements = JSON.parse(results);
            console.log(results);
            $.each(archiveelements, function(){
                $('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
            });
        },
        error: function(){
            console.log('Cannot retrieve data.');
        }
    });
});

5 个解决方案

#1


2  

I tried to run your Code and I get

我试着运行你的代码而且我得到了

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:

通过定义dataType:'json',您的结果已经被解析为数组。所以你可以这样做:

success: function (results) {
    if (results["head"]["foo"] != 0) {
        // do something
    } else if (results["head"]["bar"] == 1) {
        // do something
    }
}

this works on my computer:

这适用于我的电脑:

$.ajax({
    type: 'post',
    url: '/src/php/LoadAdminDashboardArchive.php',
    dataType: 'json',
    data: { action : 'getArchive' },
    success: function(results) {
        console.log(results);
        $.each(results, function(){
            $('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
        });
    },
    error: function(){
        console.log('Cannot retrieve data.');
    }
});

#2


1  

You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:

如果您再深入了解一下,您可以从控制台获取更多信息。或者通过记录这两个参数:

error: function(xhr, mssg) {
    console.log(xhr, mssg);
}

#3


1  

First your response is not correct,Correct response should look like this

首先你的反应不正确,正确的反应应该是这样的

[{
  "id":"1",
  "archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
  ...
}]

Second You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.

第二,你不必解析结果ie.JSON.parse不是必需的,因为dataType:'json'可能会处理json。

Finally your success method should look like this:

最后,您的成功方法应如下所示:

 success: function(results) {
            $.each(results, function(ind,el){
                $('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
            });
        },

#4


1  

As you are saying message from error-handler is showing.

正如您所说,来自错误处理程序的消息正在显示。

That means AJAX is never sent to server because of incorrect URL or any other reason.

这意味着由于URL不正确或任何其他原因,AJAX永远不会发送到服务器。

Use Firebug in Firefox and see the error in console tab.

在Firefox中使用Firebug并在控制台选项卡中查看错误。

Also I see your code

我也看到了你的代码

dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
    var archiveelements = JSON.parse(results);
}

Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.

不要使用JSON.parse(结果),因为您已经编写了dataType:'json',并且会自动解析任何类型的响应。

#5


0  

I was able to get it working and the problem was quite simple...

我能够让它工作,问题很简单......

I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.

我忘了粘贴“按钮” - 启动ajax请求的源代码。它是“提交”类型的输入,因此在成功检索到响应后默认重新加载页面...所以e.preventDefault();是要走的路。

Thanks to all of you.

感谢大家。

#1


2  

I tried to run your Code and I get

我试着运行你的代码而且我得到了

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:

通过定义dataType:'json',您的结果已经被解析为数组。所以你可以这样做:

success: function (results) {
    if (results["head"]["foo"] != 0) {
        // do something
    } else if (results["head"]["bar"] == 1) {
        // do something
    }
}

this works on my computer:

这适用于我的电脑:

$.ajax({
    type: 'post',
    url: '/src/php/LoadAdminDashboardArchive.php',
    dataType: 'json',
    data: { action : 'getArchive' },
    success: function(results) {
        console.log(results);
        $.each(results, function(){
            $('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
        });
    },
    error: function(){
        console.log('Cannot retrieve data.');
    }
});

#2


1  

You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:

如果您再深入了解一下,您可以从控制台获取更多信息。或者通过记录这两个参数:

error: function(xhr, mssg) {
    console.log(xhr, mssg);
}

#3


1  

First your response is not correct,Correct response should look like this

首先你的反应不正确,正确的反应应该是这样的

[{
  "id":"1",
  "archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
  ...
}]

Second You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.

第二,你不必解析结果ie.JSON.parse不是必需的,因为dataType:'json'可能会处理json。

Finally your success method should look like this:

最后,您的成功方法应如下所示:

 success: function(results) {
            $.each(results, function(ind,el){
                $('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
            });
        },

#4


1  

As you are saying message from error-handler is showing.

正如您所说,来自错误处理程序的消息正在显示。

That means AJAX is never sent to server because of incorrect URL or any other reason.

这意味着由于URL不正确或任何其他原因,AJAX永远不会发送到服务器。

Use Firebug in Firefox and see the error in console tab.

在Firefox中使用Firebug并在控制台选项卡中查看错误。

Also I see your code

我也看到了你的代码

dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
    var archiveelements = JSON.parse(results);
}

Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.

不要使用JSON.parse(结果),因为您已经编写了dataType:'json',并且会自动解析任何类型的响应。

#5


0  

I was able to get it working and the problem was quite simple...

我能够让它工作,问题很简单......

I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.

我忘了粘贴“按钮” - 启动ajax请求的源代码。它是“提交”类型的输入,因此在成功检索到响应后默认重新加载页面...所以e.preventDefault();是要走的路。

Thanks to all of you.

感谢大家。