jQuery.getJSON and jQuery.parseJSON return [object Object]?

后端 未结 7 1181
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 07:06

EDIT: I\'ve gotten the \"famous question\" badge with this question, so I figured I\'d come back to it and stick what happened to me right at the very tippy

7条回答
  •  天涯浪人
    2020-12-08 07:29

    The alert() function can only display a string of text. As its only parameter it takes a string or an object. The object will however be converted into a string that can be displayed.

    When fetching JSON through jQuery, the $.ajax() method will automatically parse the JSON and turn it into a JavaScript object for you. Your data variable is therefor a JavaScript object, and not a JSON string as one might expect.

    Since alert() only can display strings, when trying to alert your data object, your object will be turned into its string representation. The string representation of a JavaScript object is [object Object].

    For debug-purposes you can use console.log(data) instead. You can then inspect the object and its content through the console in your browsers developer tools.

    function init2() {
        jQuery.ajax({
            url: "/Mobile_ReportingChain.cfm",
            type: "POST",
            dataType: "json",
            async: false,
            success: function (data) {
                console.log(data);
            }
        });
    }
    

    If you for some reason still want to alert the JSON-data, then you would have to turn your data object back into a JSON-string. To do that you can make use of JSON.stringify:

    alert(JSON.stringify(data));
    

提交回复
热议问题