doukong9982 2015-04-01 12:54
浏览 103

AJAX jquery json将数组发送到php

I'm trying to send a associative array via AJAX $.post to php. Here's my code:

var request = {
        action: "add",
        requestor: req_id,
        ...
    }

    var reqDetails = $("#request_details").val();

    switch(reqDetails){
        case 1: 
            request[note] = $("#note").val();
            break;

        ...

    }

    if(oldRequest()){
        request[previousID] = $("old_id").val();
    }

    $('#req_button').toggleClass('active');
    $.post("scripts/add_request.php", {
        request_arr: JSON.stringify(request)
        }, function(data){
            console.log(data);
            $('#req_button').toggleClass('active');
    }, 'json');

And i'm simply trying to read the received data in my php script:

echo json_decode($_POST["request_arr"]);

But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.

  • 写回答

2条回答 默认 最新

  • douye5949 2015-04-01 12:58
    关注

    Check below link for your reference

    Sending an array to php from JavaScript/jQuery

    Step 1

    $.ajax({
        type: "POST",
        url: "parse_array.php",
        data:{ array : JSON.stringify(array) },
        dataType: "json",
        success: function(data) {
            alert(data.reply);
        }
    });
    

    Step 2

    You php file looks like this:

    <?php 
    
    
    
      $array = json_decode($_POST['array']);
        print_r($array); //for debugging purposes only
    
         $response = array();
         if(isset($array[$blah])) 
            $response['reply']="Success";
        else 
            $response['reply']="Failure";
    
       echo json_encode($response);
    

    Step 3

    The success function

    success: function(data) {
            console.log(data.reply);
            alert(data.reply);
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器