我可以评估的$就响应类型()在成功回拨电话? [英] Can I evaluate the response type of an $.ajax() call in success callback?

查看:107
本文介绍了我可以评估的$就响应类型()在成功回拨电话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery做一个Ajax请求远程端点。该端点将返回一个JSON对象是否有故障并且该对象将描述故障。如果申请成功,将返回HTML或XML。

我看到如何在jQuery中定义预期请求类型的一部分​​ $。阿贾克斯()通话。有没有一种方法来检测成功请求类型处理?

  $。阿贾克斯(
    {
        键入:删除,
        网址:/ SomeEndpoint
        //数据类型:HTML,
        数据:
            {
                参数2:param0val,
                参数1:param1val
            },
        成功:功能(数据){
                //数据可以是JSON或XML / HTML
            },
        错误:函数(RES,textStatus,errorThrown){
                警报('失败... :(');
            }
    }
);
 

解决方案

有你的应用程序生成正确的内容类型头(应用程序/ JSON,文本/ XML等)和处理那些你成功的回调。也许这样的事情是否行得通呢?

  XHR = $阿贾克斯(
    {
        // SNIP
        成功:功能(数据){
                VAR克拉= xhr.getResponseHeader(Content-Type的');
                如果(CT =='应用程序/ JSON'){
                    //反序列化的JSON,并继续
                }否则,如果(CT =='为text / xml'){
                    //反序列化XML和继续
                }
            },
         // SNIP
);
 

未经检验的,但它是值得一试。

I am using jQuery to make an AJAX request to a remote endpoint. That endpoint will return a JSON object if there is a failure and that object will describe the failure. If the request is successful it will return HTML or XML.

I see how to define the expected request type in jQuery as part of the $.ajax() call. Is there a way to detect the request type in the success handler?

$.ajax(
    {
        type: "DELETE",
        url: "/SomeEndpoint",
        //dataType: "html",
        data:
            {
                "Param2": param0val,
                "Param1": param1val
            },
        success: function(data) {
                //data could be JSON or XML/HTML
            },
        error: function(res, textStatus, errorThrown) {
                alert('failed... :(');
            }
    }
);

解决方案

Have you application generate correct Content-Type headers (application/json, text/xml, etc) and handle those in your success callback. Maybe something like this will work?

xhr = $.ajax(
    {
        //SNIP
        success: function(data) {
                var ct = xhr.getResponseHeader('Content-Type');
                if (ct == 'application/json') {
                    //deserialize as JSON and continue
                } else if (ct == 'text/xml') {
                    //deserialize as XML and continue
                }
            },
         //SNIP
);

Untested, but it's worth a shot.

这篇关于我可以评估的$就响应类型()在成功回拨电话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆