如何检索jquery $ .ajax对象的responseJSON属性

我有这个javascript:

$ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {}, error:function (xhr, ajaxOptions, thrownError) { dir(thrownError); dir(xhr); dir(ajaxOptions); } }); console.dir($ajax); console.dir($ajax.responseJSON); 

console.dir($ ajax)显示它有一个名为responseJSON的属性,但当我尝试使用$ ajax.responseJSON访问它时,它返回undefined: 在此处输入图像描述

嗯,当然它是未定义的,因为当你在代码的最后几行运行console时,响应还没有来自服务器。

$.ajax返回promise,您可以使用它来附加done()fail()回调,您可以在其中使用您看到的所有属性。 并且您实际上已经使用了回调errorsuccess ,并且您可以在其中运行依赖于响应中的数据的代码和其他函数。

您可以使用此技巧来获取响应:

 jQuery.when( jQuery.getJSON('DBConnect.php') ).done( function(json) { console.log(json); }); 

现在已经很晚了,但希望能帮到别人。

响应,是“数据”,成功…所以你可以访问成功的内部写入数据[0],数据[1]。

例如:

 success: function(data) { alert(data[0]); }, 

如果你想要这个响应,那么你可以在外面设置一个变量,并尝试这个:

 success: function(data) { myVar = data; }, 

希望,这个帮助。

对于那些不介意它是否同步的人,就像我一样,你可以这样做:

 $('#submit').click(function (event) { event.preventDefault(); var data = $.ajax({ type: 'POST', url: '/form', async: false, dataType: "json", data: $(form).serialize(), success: function (data) { return data; }, error: function (xhr, type, exception) { // Do your thing } }); if(data.status === 200) { $('#container').html(data.responseJSON.the_key_you_want); } }); 

它遍历运动,等待Ajax调用的响应,然后如果状态== 200则处理它,如果某些事情触发了错误,则在error函数内部处理它。

编辑选项以符合您的情况。 快乐编码:)