How to listen for returned json object with jquery

I have a page with a form that has a file input element designed for a hidden iframe. When the form is submitted in an iframe, the server processes the file and returns a json object. I'm not sure how to use jquery or plain old javascript to do this to listen on the returned object. I have code for my iframe, for example ...

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

Does anyone know how to connect jquery to listen on a json object that was sent back to the iframe? Thanks.

+3
source share
3 answers

I finally figured out how to do this ....

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

Whether it is right or not, it works.

edit - in fact, I was a little ahead of myself. here is 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 change was to make sure that in my MVC controller there was a JSONResult.ContentType = "text / plain" setting. Otherwise, I got a download dialog box.

+5
source

You should not use .load() for this kind of request. It inserts the response into the selected items. This, of course, is not what you want when talking about objects. Try $.getJSON() (or $.post() using 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'); 
+4
source

You should use load as follows:

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

But for Ajax and JSON you have to use post, $. getJSON or $. get or $. post or $ .ajax (these functions also take as a parameter a callback function with arguments containing the result).

0
source

Source: https://habr.com/ru/post/925854/


All Articles