如何用jquery监听返回的json对象

我有一个页面,其表单包含一个文件上传输入项目,目标是隐藏的iframe。 当表单发布到iframe时,服务器处理该文件并返回一个json对象。 我不确定如何使用jquery或普通的旧javascript来监听返回的对象。 我为我的iframe设置了一些代码,例如……

$("#upload_target").load(function () { //what to do here - how do I get the json object? }); 

有谁知道如何连接jquery来监听发送回iframe的json对象? 谢谢。

我终于想出了怎么做……

 $("#upload_target").load(function (data) { if (data != null){ var obj = jQuery.parseJSON(data); //...work with obj here. } }); 

无论是否正确,它都有效。

编辑 – 实际上我有点领先于自己。 这是正确的代码….

 $("#upload_target").load(function (){ var retval = $(frames['upload_target'].document).text(); if (retval != null) { try{ var obj = jQuery.parseJSON(retval); //...work with obj here. }catch(err){} } }); 

我必须改变的一件事是确保我的MVC控制器操作设置JSONResult.ContentType =“text / plain”。 否则我得到一个保存为下载对话框。

您不应该使用.load()来处理此类请求。 它将响应插入到选定的元素中。 在谈论对象时,这肯定不是你想要的。 尝试使用json作为dataType $.getJSON() (或$.post() ):

 // $.getJSON uses HTTP GET $.getJSON('http://example.com/ajax', function (data) { // data is an object }); // the same with $.post for POST requests $.post('http://example.com/ajax', function (data) { // data is an object }, 'json'); 

你应该这样使用load :

 $("#upload_target").load( "http://example.com/myjson.php", function(response, status, xhr) { }); 

但对于Ajax和JSON,您应该使用post, $ .getJSON或$ .get ,或$ .post或$ .ajax (这些函数也将参数作为包含结果的参数的回调函数)。