简体   繁体   English

JSON.Parse导致JavaScript错误

[英]JSON.Parse causes error in javascript

I'm having some problems with JSON.Parse in my code and I cant find the reason of this I have a function which call two ajax functions, one on the start and another on the success function . 我在代码中遇到了JSON.Parse的问题,我找不到这个原因,我有一个函数可以调用两个ajax函数,一个在start上,另一个在success函数上。 Its working fine but when I'm try to parse the second one response the code breaks without giving any error and the real mystery is JSON.parse(object); 它工作正常,但是当我尝试解析第二个响应时,代码会中断而不会给出任何错误,真正的奥秘在于JSON.parse(object); dosent give any problem but when I use a variable to store the result like this var list =JSON.parse(object); 剂量给任何问题,但当我使用一个变量来存储结果像这样var list =JSON.parse(object); my code broke and I dont what is the reason behind this my current code is given below 我的代码坏了,我不知道背后的原因是什么

function getData()
{
            $.ajax({
                type: "POST",
                url: "MyPage.aspx/GetData",
                data: JSON.stringify({ data: data})
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var result = JSON.parse(response.d);
                    var temp = 0;
                    for (var i = 0; i < result.length; i++) {

                        if (result[i].data > 1) {
                            var subList = JSON.parsegetFullData (result[i].id));
                        }

                }
            });
}
     function getFullData (id) {
            var sublist;
            $.ajax({
                type: "POST",
                url: "MyPage.aspx/GetData2",
                data: JSON.stringify({ id: id }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    return response.d;
                }
            });

        }

any thought will help a lot 任何想法都会有很大帮助

When you use $.ajax with dataType:"json" , the response is already parsed for you. 当您将$.ajaxdataType:"json" ,响应已为您解析。 And there doesn't seem to be a reason to try to parse response.d . 而且似乎没有理由尝试解析response.d

Simply use 只需使用

$.ajax({
           type: "POST",
           url: "MyPage.aspx/GetData",
           data: JSON.stringify({ data: data})
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (results) {
                for (var i = 0; i < results.length; i++) {
                    console.log(results[i].id, results[i].LastName);

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

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