views:

31

answers:

2

I need to make an Ajax request, but its response may vary and it's decided on the server side. Is there any way to know what type the response is?

It may look similar to:

$.post(url, pars, function (response, type) {
    if (type=='json') ...
    if (type=='html') ...
});

Thanks

A: 

If you have control of the server-side code as well, the easiest thing will probably be to include a parameter with a value to specify the format.

Here's an example where I did the same type of thing you're describing. I loaded a table with customer values from data returned in xml, json, or string format, all driven by the value my server-side code returned as the format parameter:

function checkCusts(id, format, resultRegion) {
  var address = "cust-lookup.jsp";
  var data = "cust_id_list=" + getValue(id) + "&format=" + format;

  if (address != "") {
    ajaxPost(address, data,
    function(request) {
      parseCustomers(request, format, resultRegion);
    });
  }
}

function parseCustomers(request, format, resultRegion) {
  if ((request.readyState == 4) && (request.status == 200)) {
    var headings = new Array("Customer ID", "First Name", "Last Name", "Balance");
    var rows = null, customers = null;

    if ("xml" == format) {
      var xmlDocument = request.responseXML;
      customers = xmlDocument.getElementsByTagName("customer");
      rows = new Array(customers.length);
      var subElementNames = ["cust_id", "first_name", "last_name", "balance"];
      for (var i=0; i<customers.length; i++) {
        rows[i] = getElementValues(customers[i], subElementNames);
      }
    } else if ("json" == format) {
      var rawData = request.responseText;
      var data = eval("(" + rawData + ")");
      rows = data.customers;
    } else if ("string" == format) {
      var rawData = request.responseText;
      var rowStrings = rawData.split(/[\n\r]+/);
      rows = new Array(rowStrings.length -1);
      for (var i=1; i<rowStrings.length; i++) {
        rows[i-1] = rowStrings[i].split("#");
      }
    }

    var table = getTable(headings, rows);
    htmlInsert(resultRegion, table);
  }
}
JGB146
+1  A: 

There's no built-in way to do this, it's determined and tossed away by jQuery.httpData (note: it will be jquery.ajax.httpData in 1.4.3).

Though you can take a look at the httpData source and run the same functions yourself, that's a bit wasteful, since jQuery's doing it already. I

If your choices are only json or html, you could check typeof response, it should be "string" for HTML, otherwise you have JSON, which you could also check and be sure about as well, for example: type && type.propertyAlwaysThere.

Nick Craver
Well, it's a pity jQuery doesn't allow this on data reception, but your idea fits in my current problem. Thanks.
Sinuhe
Mmm, I've tried it, but it doesn't work... I always get typeof(response)=='string'... I think a similar but clumsy solution would be try { eval(response); /*json */ } catch (e) { /* html */ }
Sinuhe
@Sinuhe - The third param to your success is the XmlHttpRequest, try `function(resp, status, xhr) { alert(xhr.getResponseHeader("content-type")); }` what are you getting for JSON vs html?
Nick Craver
Oh, my fault! I did not put a content-type header when creating JSON object. I'll try again ;)
Sinuhe