weixin_33692284 2012-09-13 02:45 采纳率: 0%
浏览 49

jQuery json处理错误

I'm using jquery's ajax function to send json to a php script and return a json set of values for front end processing.

The php script is sending the json and I am able to echo out the json from the php script and retrieve via the success function parameter.

My question is how should I be handling errors. Is there a preferred way to send exception information (validation, etc.) back to the front end, and indicate that an error has occurred in php. Should I just be packaging up such information in a json object and checking what was received.

Thanks,

$.ajax({
   url: 'gear.php',
   type: 'POST',
   data: {'json': JSON.stringify(shopping)},
   success: function(data){
      console.info(data);
   },
   error: function(data){
      console.info(data);
   }
});
  • 写回答

1条回答 默认 最新

  • weixin_33743703 2012-09-13 02:53
    关注

    I would recommend both approaches actually. Use the error: block to catch any server side errors (i.e. 404, 500 errors, etc), but for business exceptions respond with a different block of JSON that you can check for. Do that in success:.

    For example:

    $.ajax({
       url: 'gear.php',
       type: 'POST',
       data: {'json': JSON.stringify(shopping)},
       success: function(data){
          if (data.error_message){
              alert(data.error_message);
          } else {
              console.info(data);
          }
       },
       error: function(data){
          console.info(data); //popup an uh-oh message.
       }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入