Uncaught SyntaxError: Unexpected token u

我正在尝试从获取请求中获取 JSON 响应。但是,我收到以下错误: Uncaught SyntaxError: Unexpected token u 。我知道 rails 路线有效,因为我确实在控制台中成功加载了响应。

Ajax 响应应该在复选框更改并被选中时启动。

为什么我从 $.parseJSON 收到此错误?

导轨控制器

def providers
   @providers = User.order("last_name ASC, first_name ASC, middle_name ASC").where("provider_flag = ? and inactive_flag = ? and del_flag = ?", true, false, false).select("id, CONCAT(IFNULL(last_name,''), ', ', IFNULL(first_name,''), IFNULL(middle_name,'')) AS full_name");

    respond_to do |format|
        format.json { render :json => { :providers =>  @providers.to_json}, :status => :ok }
        # format.json { render :json => @providers.to_json }
    end
end

Javascript

$('#provider_chk').change(function() {
        if($(this).is(":checked")) {
            $.ajax({
                url: '<%= providers_schedule_index_path %>',
                type: 'GET',
                dataType: 'json',
                data: {
                    authenticity_token: $('meta[name=csrf-token]').attr('content')
                },
                success: function(data) {
                    console.log('loaded successfully.');
                    var providers = $.parseJSON(data.responseText)['providers'];
                    providers_count = $(providers).size();
                    console.log(providers);
                    console.log(providers_count);
                },
                error: function(data) {
                    console.log("An error has occurred!")    
                }
            });
        } else {
            $('#providers_results').empty();
        }
    });

JSON 响应

providers: "[{"id":2,"full_name":"Test, User"}]"
stack overflow Uncaught SyntaxError: Unexpected token u
原文答案

答案:

作者头像

Your JSON response should look more like this:

providers: [{"id":2,"full_name":"Test, User"}]

The outermost quotations marks aren't needed.

If you really need the outer quote marks, you need to escape the inner ones.

作者头像

In $.ajax({}), add the property "async:false". parseJSON hasn't gotten that JSON yet - it's immediately trying to operate on undefined ("u") and throwing the error.

作者头像

Remove to_json since you are already telling rails to return json

format.json { render :json => { :providers => @providers }, :status => :ok }