如何在变量中获取json字符串

时间:2016-09-06 09:19:32

标签: javascript jquery json ajax

我把json字符串放在ajax中就像这样的函数

  $.ajax({
        type: "POST",
        url: "http://localhost/./Service/GetPageInfo",
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify({

            filename: filename
        }),
        success: function (data) {
            alert('Success');

        },
        error: function () {
            alert('Error');
        }
    });

这里我得到像

这样的数据
[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]

我希望它在像

这样的变量中
var  myjsonobject =[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]

3 个答案:

答案 0 :(得分:0)

你去了:

$.ajax({
    type: "POST",
    url: "http://localhost/./Service/GetPageInfo",
    dataType: "json",
    contentType: 'application/json',
    data: JSON.stringify({

        filename: filename
    }),
    success: function (data) {
        alert('Success');
        var jsonobject = data;

    },
    error: function () {
        alert('Error');
    }
});

另外,我强烈建议您使用promises进行API调用:https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise

答案 1 :(得分:0)

 var jsonobject= null;

$.ajax({
        type: "POST",
        url: "http://localhost/./Service/GetPageInfo",
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify({

            filename: filename
        }),
        success: function (data) {
            jsonobject=data;
            alert('Success');

        },
        error: function () {
            alert('Error');
        }
    });

如果你想等待ajax响应并填充变量,那么在ajax请求选项中传递async: false

答案 2 :(得分:0)

根据您的评论,您需要在成功处理程序中解析JSON,

Key is Hi value is 2
Key is Hello value is 1
Key is Welcome value is 1
Key is Jin value is 1