jQuery ajax returned data: json and html mix?

前端 未结 3 1876
温柔的废话
温柔的废话 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 16:49

    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.

提交回复
热议问题