jQuery ajax returned data: json and html mix?

前端 未结 3 1878
温柔的废话
温柔的废话 2021-01-21 16:41

I have this ajax request to get the data from my server, and the dataType is always html by default. But sometimes it would return json from the server

3条回答
  •  佛祖请我去吃肉
    2021-01-21 17:10

    may be you need to handle it like this

    try{
    var response=jQuery.parseJSON('response from server');
    if(typeof response =='object')
     {
        //control would reach this point if the data is returned as json
     }
     else
     {
        //control would reach this point if data is plain text  
         if(response ===false)
         {
             //the response was a string "false", parseJSON will convert it to boolean false
         }
         else
         {
              //the response was something else
         }
     }
    }
    catch(exp){
        //controls reaches here, if the data is html
    }
    

    Since you need to check the html data as well, you may need to take care of this,

    Might also need to use a try / catch for exceptions if it is possible that parseJSON is going to be dealing with something other than JSON values (i.e. HTML)

    REF:How can I check if a value is a json object?

    EDIT:Edited to make code more precise towards solution

提交回复
热议问题