为什么我需要从jQuery.get()解析JSON对象?

时间:2016-09-02 04:11:00

标签: jquery json

在我的javascript中,我有一个jQuery ajax get请求:

router.post('/jobs', function (req, res, next) {
    var job = new Job(req.body.jobDetails);
    var examples = req.body.examples;

    console.log("JOB DETAILS");
    console.log(req.body.jobDetails);

    console.log("EXAMPLES");
    console.log(req.body.examples);

    //save job
    job.save(function (err, job) {
          console.log(err);
    });

    //save examples
    for(i=0; i<examples.length;i++){

        var eg = new Example({content: examples[i]});
        eg.job=job;

        eg.save(function (err, eg){
            console.log(err);
        });

        job.examples.push(eg);
        job.save(function(err,job){
            console.log(err);
        });
    }
});

在萤火虫中,我可以看到响应标题:

    $.get(uri, callback_function, 'json');  

回复内容:

 Content-Type   application/json 

Net中甚至还有一个JSON选项卡 - &gt; XHR显示返回的数据漂亮打印。

但是,为什么在我的回调函数中我需要解析我得到的数据?

{ "status": true, "data": "my test output" }    

从文件中:
https://api.jquery.com/jQuery.get/
      jQuery.get(url [,data] [,success] [,dataType])
      dataType类型:字符串       服务器所需的数据类型。默认值:智能猜测(xml,json,脚本,文本,html)。

由于我都期待并获得一个JSON对象(请参阅HTTP响应头),为什么我需要解析看似仅仅是字符串的内容?

1 个答案:

答案 0 :(得分:0)

目前它只是一个字符串,基本上,因为你需要解析它以将其转换为javascript对象。

你可以在调试器中看到它格式化,因为我希望调试器也为你解析它,因为显示一个长字符串会没那么有用。

因此,您进行解析,以便您可以使用您需要的语言获得的结果,在本例中为javascript。