dongqucheng3851 2015-08-13 07:53
浏览 52
已采纳

如何在jQuery post方法中检查从PHP返回的数据类型

Type of data

[{"id":"1","value":"Google"},{"id":"2","value":"Samsung"}]

Now I have a general function that performs certain actions based on the type of data being returned.

for this particular data I am checking if it is array or not. In order to check the type of the data being return I am using the following custom function.

function typeOf (obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

now if I call typeOf(1) it returns "number" as answer

if I call typeOf("foo") it return "string" as answer

The Problem

calling typeOf(data) where data = [{"id":"1","value":"Google"},{"id":"2","value":"Samsung"}] being echoed from php page it gives "string" as answer

It only returns array if the recieved array type data variable is passed through following function as

data = jQuery.parseJSON(data);

Now, I understand it might be the case that what ever gets echoed from php comes in string form but isn't there any way it can be changed as my php page is doing following

echo json_encode(array(array(some_key=>some_data)));
  • 写回答

3条回答 默认 最新

  • doufeng3602 2015-08-13 20:32
    关注

    For jQuery to know that you're sending JSON data, the server has to respond with the correct Content-Type header. In PHP, this can easily be achieved by calling header('Content-Type: application/json'); before any output, and jQuery will attempt to parse the response.

    This will result in the data parameter of your success handler to be an object containing the values from the JSON. Make sure to check that you get an object type data variable, because any other type should indicate that malformed JSON data is coming from your server.

    $.ajax({
        url: '/endpoint.php',
        method: "POST",
        data: {key:'value'},
        success: function(data){
            if (typeof data !== 'object')
                return console.error('Invalid data', data);
    
            // Do something with the response
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料