2017-04-13 36 views
0

我的应用程序向服务器发送ajax POST,如果服务器验证失败,服务器将stringDictionary<string, object>返回给客户端。如何确定json对象是否是序列化字典?

因此,如果服务器发送Dictionary然后系列化responseText是jQuery是收到类似

"{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}" 

我也有相应的可在客户端responseJSON

$.ajax({ 
     cache: false, 
     type: 'POST', 
     url: url, 
     data: data    
    })    
    .fail(function (response, textStatus, errorThrown) {   
      if (response.status === '400') { 
       if ($.isArray(response.responseJSON)) { 
        $.each(response.responseJSON, function (index, value) { 
         //do something 
        }) 
       } 
       else if ($.type(response.responseJSON) === 'string') { 
         // do something 
       } 
      }    
     } 

当响应是字典时,.isArray方法返回false。我如何确定responseJSON是否为Dictionary以及我如何循环?

注意
object该服务器发回

+0

的可能的复制[检查如果一个值是在JavaScript对象(http://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript ) – Hamms

+0

JavaScript中没有'Dictionary'类型。你得到一个JSON字符串的方式。一旦反序列化,你就有一个“对象”。 –

+0

你在做什么没有意义。将dataType设置为json并使用成功处理程序处理已经是对象的数据。如果失败,则responseText无效json或者有其他连接错误 – charlietfl

回答

0

你试图解释的反应,看看它最终被一个对象(或“词典”)。如果响应看起来是JSON,并且它的结果也是一个对象(“Dictionary”),那么您知道该字符串是一个对象(“Dictionary”)。

下面的代码应该列出所有必要的技术,以便将它集成到您​​自己的代码中。

var thatResponseJson = "{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}"; 
try { 
    var result = JSON.parse(thatResponseJson); 
    if (result instanceof Array) { 
     // An Array 
    } else if (typeof result === 'object' && thatResponseJson[0] === '{') { 
     // Usually an object 
    } else if (typeof result === 'string') { 
     // A string 
    } else { 
     // Neither an Array, some other kind of object, or a string 
    } 
} catch (err) { 
    // Not valid JSON 
} 
+0

没有必要的大部分。设置'dataType:'json''时,'$ .ajax'会在内部验证json。如果有效的json返回并且不存在CORS问题,将不会失败。另外可以使用jQuery核心'$ .type()'工具..将返回对象vs数组与字符串http://api.jquery.com/jQuery.type/ – charlietfl

+0

对我来说很好! – Brian

相关问题