最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery ajax returned data: json and html mix? - Stack Overflow

programmeradmin0浏览0评论

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, so I want to check if the returned data is html then execute A else execute B. Is it possible?

My jquery,

 $.ajax({
     type: "GET",
     dataType: "html",
     url: request_url,
     context: $('#meat'),
     async: true,
     beforeSend: function () {},
     success: function (returndata, status, jqXHR) {
         if ($.parseJSON(returndata) === false) A;
         else B.
     }
 });

I get this error when the returned data is html,

SyntaxError: JSON.parse: unexpected character

So how can I make this code versatile?

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, so I want to check if the returned data is html then execute A else execute B. Is it possible?

My jquery,

 $.ajax({
     type: "GET",
     dataType: "html",
     url: request_url,
     context: $('#meat'),
     async: true,
     beforeSend: function () {},
     success: function (returndata, status, jqXHR) {
         if ($.parseJSON(returndata) === false) A;
         else B.
     }
 });

I get this error when the returned data is html,

SyntaxError: JSON.parse: unexpected character

So how can I make this code versatile?

Share Improve this question edited May 17, 2014 at 23:09 Pascal 1,2848 silver badges13 bronze badges asked Dec 23, 2013 at 12:13 RunRun 57.3k178 gold badges463 silver badges771 bronze badges 3
  • be sure you are parsing array to the json_encode() ? – underscore Commented Dec 23, 2013 at 12:15
  • yes for the json data. but i dont use json_encode if the returned data is html. – Run Commented Dec 23, 2013 at 12:15
  • 1 you can try this: dataType: "json" || "html", and you can try using typeof() method for the return data that if that is object the process it as json. – Jai Commented Dec 23, 2013 at 12:18
Add a ment  | 

3 Answers 3

Reset to default 6

I'm not sure if there is a better way, but you could try... catch

$.ajax({
      type:       "GET",
      url:        request_url,
      context:    $('#meat'),
      async:      true,
      beforeSend: function() {
      },
      success: function (returndata, status, jqXHR) {
        var parsed;
        try
        {
            parsed = $.parseJSON(returndata);
            // Execute B
        }
        catch(e)
        {
           // treat as html then
           // do parsing here
           parsed = returnData;
           // Execute A
        }
      }

});

Essentially, your code is just plain wrong - your serverside API is violating all principles of predictability if the return type can vary in an inconsistent manner. Your code should never have to guess at the type of the returned data.

Having said that, a simple try/catch will help as a workaround for the erratic behaviour if you don't want to fix it. Ie.

try {
    if ($.parseJSON(returndata) === false) A;
} catch(e) {
    // Treat as HTML here.
}

It's not pretty, but that's what you get for having an unpredictable API that isn't pretty to begin with.

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

发布评论

评论列表(0)

  1. 暂无评论