dsfo22654 2015-04-18 17:35
浏览 73
已采纳

AJAX第二次不会获得JSON数据

I'm sending Ajax request to a php file, that file returns an JSON array of the submitted data, the first time is great, it sends the data and gets it, so i can use it, but second time it gives me an error

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

My goal is to validate the data in the php file, if the data is not validated then i'm adding an error classes to the fields that are not validated, then the user correct those fields, and sends the form again, without refreshing.

My testing shows that its working for the first time, but when i want to send the form the second time, it gives me the above error, any clues what it can be?

AJAX :

$('#ajax').submit('submit', function(){

var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};

that.find('[name]').each(function(index, value){
    var that = $(this),
    name = that.attr('name'),
    value = that.val();

    data[name] = value;
});

$.ajax({
    url: url,
    type: type,
    data: data,
    cache:false,

    success: function(response){
        var json = response,
        obj = JSON.parse(json);
        if(obj.title == 'Mrs.'){
        //  $('#title').addClass('has-warning');
            $(function () {
              $('#name').tooltip({ 'title': 'Please fill name'});
            });
        }
        alert(obj.title);
    }

});
return false;
});

PHP file:

if(Input::exists()){
if(token::check(Input::get('token'))){

    echo json_encode(
    array(
        "title" => Input::get('title')
        )
    );
}

}
  • 写回答

1条回答 默认 最新

  • dpt8910 2015-04-18 17:44
    关注

    Your token check is the culprit here. It's not working the second time because it's returning an empty response. This is because you probably need to recreate a new Token and send it with the first response. To test if this is the issue, just write :

    if(Input::exists()){
     if(token::check(Input::get('token'))){
    
      echo json_encode(
      array(
        "title" => Input::get('title')
        )
      );
     }else{
       echo json_encode(
         array("title" => 'See? You need to update token')
       );
     }
    }
    

    You should regenerate a new Token and then update it's value in the form :

    echo json_encode(
         array("newToken" => Token::generate() )
       );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退