2

What I want to do is get a JSON object and an HTML view from a single AJAX call.

My current implementation is the JSON object is hidden in some part of the html and just parsed client side.

Is this good practice? Is there a better way of doing this?

wnoveno
  • 546
  • 3
  • 9
  • 25
  • You could encode the JSON object into a data attribute on an HTML element – Petah Dec 12 '11 at 02:52
  • Can you store the view as a string in a key of the json object? That would be easier than having to parse the json out of the html view. – jdi Dec 12 '11 at 02:53

4 Answers4

4

Return a JSON object with the HTML inside:

{ "a": "data", "b" : "data", "view" : "<html>...</html>" }
Jason
  • 3,379
  • 25
  • 32
0

Another option (as the option to alter the content type of the original request seems obvious to everyone here) would be to send a custom JSON header.

XXX-JSON-Payload: {a:1, b:2}

And read that header from JS (see getResponseHeader is not a function for a jQuery method of doing that).

Community
  • 1
  • 1
Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
0

I would return JSON from the AJAX call, and in one of the JSON attributes, store the encoded HTML. Seems quite a bit simpler and stable than trying to parse JSON back out of an HTML response.

ziesemer
  • 27,712
  • 8
  • 86
  • 94
0

You can do it by embedding your JSON into an HTML elements data attribute:

Assuming your ajax call returns this:

<json data-obj='{"my":"json","data":7}'/>
<div>My View</div>

Then the following will load the view, and extract the data from the attribute

<div id="content"></div>
<script>
    $('#content').load('ajax.php', function(data) {
        $(data).siblings('json').remove().data('obj');
    });
</script>

(tested with jQuery v1.7.1)

Petah
  • 45,477
  • 28
  • 157
  • 213