dongxingji3882 2013-10-10 17:18
浏览 186
已采纳

将json传递给php并从php接收数据的问题

My problem is how JQuery knows when to receive data, when I watch the browser's console I see that GET call is first and then the POST call is second. It should be POST first, then GET.

I tried solving my problem with .ready,and with some IF statements and so on but I still have not achieved what I wanted to achieve. Should I use some events?

My Javscript:

 (function($) {
   $(document).ready(function() {
     $("form#userdata").submit(function(){
       $.post( "savedata.php", $("form#userdata").serialize())
         .done(function( data ) {
           alert( "Send data" + data );
        });
       return false;
       alert("Error by passing data to php");
     });

 })})(jQuery);

 $.when($.ajax("savedata.php")).then(function(){
     $.get("savedata.php", function(data){
            alert("Php returns validation errors:+data);
     });
 });

My php script:

 // Get POST data
 $postData = $_POST;

 // Print out for testing
 // print_r($postData);

 // Read data
 $fistname = $_POST['firstname'];
 $surname=$_POST['lastname'];
 $email=$_POST['email'];

 // VALIDATION


 // Build return array and return JSON
 $returnData = $postData;

 //print(json_encode($returnData));
 echo json_encode($returnData);
 ?>
  • 写回答

3条回答 默认 最新

  • doufan3958 2013-10-10 17:37
    关注

    You can try something like this:

    PHP:

    // Get POST data
     $postData = $_POST;
    
     // Print out for testing
     // print_r($postData);
    
     // Read data
     $fistname = $_POST['firstname'];
     $surname=$_POST['lastname'];
     $email=$_POST['email'];
    
     // VALIDATION
    
     if(//validationError){
        echo json_encode(array('error' => //Your error message here));
        exit();
     }
     $returnData = $postData;
    
     //print(json_encode($returnData));
     echo json_encode(array('success' => $returnData));
     ?>
    

    Then...

    JS:

    (function($) {
    
       $(document).ready(function() {
    
         $("form#userdata").submit(function(){
    
           $.post("savedata.php", $("form#userdata").serialize())
            .done(function( data ) {
               if(data.error)
                  alert("Validation error: " + data.error);
               else
                  alert( "Send data" + data.success );
            })
            .fail(function(){
               alert("Error by passing data to php");
            });
         });
    
     })})(jQuery);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?