Converting AJAX return data to JSON

此生再无相见时 提交于 2019-12-01 08:03:13

Explicitly instruct jQuery to treat the response as text:

$.ajax({
  // ...
  dataType: "text",
  // ...
});

You will then be able to get the JSON string. However, if you plan to convert it to a JS value thereafter, let me stop you: jQuery can do that for you automatically. If you specify the dataType to "json", or just let jQuery make an intelligent guess, the data argument passed to the success: function will be the parsed JSON object.

matchew

why not use $.getJson()

which is equivilant to

 $.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

which you should then be able to do the following:

$.getJSON('file.json', function(data) {
$.each(data, function(i) {
       console.log(data[i]);
     });
    });

edit

perhaps, I am misunderstanding the problem.

EDIT #2 Perhaps this question would help: Is there a version of $getJSON that doesn't use a call back?

which suggests using this:

$.ajax({
    type: 'GET',
    url: 'whatever',
    dataType: 'json',
    success: function(data) { console.log(data);},
    data: {},
    async: false
});

which of course, looks like what you have, so I feel I need to step back and reanalyze the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!