jQuery ajax return readyState 1 or incorrect data

2019-07-11 06:15发布

I write script for Wordpress plugin and have problem with ajax response. When i want get json file, jQuery.ajax return {readyState: 1}. jQuery.ajax with async: false return plain text although I have dataType: 'json'.

App.Language = {

    GetLanguageFile: function(lang) {
        var LangFile = GetJsonLanguageFile(lang);
        return LangFile;
    },

}

function GetJsonLanguageFile(lang) {
    var json = $.ajax({
        url: ajaxurl,
        type: 'POST',
        dataType: 'json',
        // async: false,
        data: {action:'adminajax',method:'GetJsonLanguageFile',language: lang},
    })

    return json;
}

When function returned readyState: 1, in console I have object with key "responseText" and plain text result from json file but I can't get this key value, and when function is async, returned is object and I can get result but it's a plain text, although i have dataType: 'json'.

What I do wrong? How to make normal object from this json file content?

1条回答
2楼-- · 2019-07-11 06:36

Ajax call returns promise so you have to use done menthod to work with result, for example:

 function GetJsonLanguageFile(url, lang) {
        return $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            // async: false,
            data: {action:'adminajax',method:'GetJsonLanguageFile',language: lang},
        });
}

GetJsonLanguageFile('some.url', lang).done(function(data) {
  // if it returns string insted of JSON try it:
  data = $.parseJSON(data);
  // do rest
  // window.json = data;
});
查看更多
登录 后发表回答