how to listen for returned json object with jquery
I have a page with a form that has a file upload input item targeted to a hidden iframe. When the form is posted to the iframe the server processes the file and returns a json object. I'm not sure how to use jquery, or plain ol开发者_JS百科d javascript for that matter, to listen for the returned object. I have some code set up for my iframe such as...
$("#upload_target").load(function () {
//what to do here - how do I get the json object?
});
Does anyone know how to wire up jquery to listen for the json object that's sent back to the iframe? Thanks.
I finally figured out how to do it....
$("#upload_target").load(function (data) {
if (data != null){
var obj = jQuery.parseJSON(data);
//...work with obj here.
}
});
Whether it's the right way or not, it works.
edit - actually I got a bit ahead of myself. here's the correct code....
$("#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){}
}
});
One thing I had to also change was making sure that my MVC controller action was setting the JSONResult.ContentType = "text/plain". Otherwise I was getting a save as download dialog.
You should not use .load()
for this kind of request. It inserts the response into the selected elements. That is certainly not what you want when talking about objects. Try $.getJSON()
(or $.post()
with json
as dataType
):
// $.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');
You should use load this way:
$("#upload_target").load(
"http://example.com/myjson.php",
function(response, status, xhr) {
});
But for Ajax and JSON you should use post, $.getJSON, or $.get, or $.post or $.ajax (those functions also take as a parameter a callback function with arguments containing the result).
精彩评论