sinuhepop
sinuhepop

Reputation: 20316

jQuery: get the type of an Ajax response

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') ...
});

Upvotes: 1

Views: 2775

Answers (2)

Nick Craver
Nick Craver

Reputation: 630399

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.

Upvotes: 2

Jeffrey Blake
Jeffrey Blake

Reputation: 9709

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);
  }
}

Upvotes: 2

Related Questions