How to find out if the returned $ .ajax () data was from html or json?

I have a form that submits to the server via jQuery .ajax()POST. If the form has passed the server-side validation, the server will return the result in HTML for the client end to update its presentation accordingly. If, however, the form does not pass validation, the server will return the result in JSON, which consists of validation errors.

Both types of result will fall into the handler success .ajax(). Since both types are possible, the handler needs a way to determine if the result is HTML or JSON. How can i do this?

Note. At first glance, my question looks just like this existing SO question , but they do not match. There is only one possible data type (HTML or JSON) in this question , while my problem is finding a way to deal with the two possible data types (HTML and JSON).

+5
source share
5 answers

For json data typeof(data)will be object. For html data it will be string.

At least the data returned from ASP.NET MVC3 actions works. I assume this is a mime type that decides how jquery handles the returned data.

+3
source

dataType , jQuery MIME:

dataTypeString

: Intelligent Guess (xml, json, script html)

, . , jQuery MIME

ref: http://api.jquery.com/jQuery.ajax/

+5

100% , , jQuery, XSS, , , JavaScript eval().

@SLaks eval(), .

$.parseJSON JSON

function ajaxResponse(raw_data){
  try{
    // eval("var response="+raw_data); // try and avoid this if possible
    var response = $.parseJSON(raw_data);
    if (response){
      // We have a JSON inside the 'response' variable!
    }
  } catch(e){
    // We do not have a JSON.
    // Probably HTML content.
    // Might be a malformed JSON.
  }
}

, , JSON, HTML.

, dataType, $.ajax(), text, jQuery .


, - .
JSON? - :

{"err":"","html":"<div>foobar<\/div>"} 

:

{"err":"1","message":"You did not foo all of your bars yet!"} 
+2

typeof, , .

FIDDLE

+2

JSON HTML-?

JSON :

{
  //s=status, d=data
  "s":0, //0 means success, other numbers are for different errors
  "d":{ /* Other JSON object or string here */ }
}

So, in your case, you would do something like this (pseudo):

if (StuffIsValid()) {
    ResponseWrite('{"s":0,"d":"<html>html code here</html>"}');
} else {
    ResponseWrite('{"s":1,"d":{"errlist":["err1","err2"]}}');
}

Of course, you will want to use the built-in JSON library to select your server language instead of using strings.

Then in your jQuery callback successI will do a check on the value of s.

$.ajax({
    url: 'url',
    dataType: 'json',
    success: function(data) {
        if (data) {
            //We have a JSON object
            if (data.s === 0) {
                //Success!
                //Do stuff with data.d as a string
            } else if (data.s === 1) {
                //Failed validation
                //Do stuff with data.d as an object
            } else {
                //How did this happen?
            }
        } else {
            //Uh oh, no object, user must have been logged out (or something)
        }
    });

This is especially useful if the user must be logged in to access the page you submit, as you can catch the fact that the returned data was not a JSON object.

+1
source

All Articles